为什么我的代码在完成之前会一直返回?

时间:2015-03-24 09:19:51

标签: c++ visual-studio-2010

为什么我的代码无法正常运行?一旦它到达if else语句,它就会从用户那里获得一个输入,然后在我输入任何其他内容之前退出。我不确定是否由于功能没有正确返回,但我真的很感激一些帮助。感谢。

#include <iostream>
#include <fstream>

using namespace std;

void studentenrollment (char answer);

int main()
{
    char answer;                                                                    //declaring variables for main
    cout << "Welcome to Luton Sixth Form" << endl;                                   //greeting the user
    cout << "Please State if you are enrolled or not at the sixth form: Y/N" << endl;//giving user options
    cin >> answer;//taking options from user
    studentenrollment(answer);                                                       //calling student enrollment function 

    return 0;
}

void studentenrollment (char answer)
{
    unsigned char name;
    int dob;
    if (answer=='Y'||answer=='y')
    {

        cout << "Welcome to higher education" << endl;
        cout << "Please state your name" << endl;
        cin >> name;
        ofstream myfile;
        myfile.open("StudentAccess.txt");
        myfile << name << endl;
        myfile.close();
        cout << "Your name is now saved, you have access to the gateway" << endl;
    }

    else if(answer=='N'||answer=='n')
    {
        cout << "Please state your name" << endl;
        cin >> name;
        cout << "Please enter your date of birth" << endl;
        cin >> dob;
        ofstream myfile;
        myfile.open("StudentEnrollment.txt");
        myfile << name << dob << endl;
        myfile.close();
        cout << "You will now go through enrollment" << endl;
    }

//    return 0;
}

3 个答案:

答案 0 :(得分:1)

unsigned char name;看起来不正确。选择char name[MAX_LENGTH];std::string name;

会发生什么

cin >> name;  // Read just first character
cin >> dob;   // Try to read number, where rest of the name is left in the stream buffer

除非名字是1个字母,否则这看起来肯定是错误的。

答案 1 :(得分:1)

问题可能是这样的:

cin >> name;

您输入了姓名,但将其存储在name - 仅unsigned char。使用更大的数组来存储名称。

答案 2 :(得分:0)

如果变量 name 包含多个字符,则无法将其声明为 unsigned char ,您可以将其声明为 std :: string 。记得

#include<string>