【发布时间】:2011-10-12 08:25:23
【问题描述】:
由于某些奇怪的原因,当我将输入行 cin.getline(oneLine, 80); 放入此 else if 块时,它被完全忽略了。我不明白为什么,因为当我将它移到程序中的其他位置时,它可以工作。
else if (choice == "user-id")
{
cout << endl << "Enter a full name e.g. John Smith ";
char oneLine[80];
cin.getline(oneLine, 80);
cout << oneLine;
}
这是我的其余代码。我是 C++ 新手,所以我确信我的许多约定充其量可能是有问题的。
int main( )
{
while (true)
{
int pause;
string choice = "proceed";
string nameGiven;
string userIdGiven;
string result;
using namespace std ;
while ((choice != "name") && (choice != "user-id"))
{
cout << "Would you like to search for a name or user-id? ";
cin >> choice;
if ((choice != "name") && (choice != "user-id"))
cout <<"Please enter a valid choice (name or user-id)" << endl;
}
if (choice == "name")
{
string dataType = "int";
while (true)
{
cout << endl << "Enter a valid user id (4 digit maximum) ";
cin >> userIdGiven;
if (valid(userIdGiven))
break;
else
cout << endl << "Not a valid number. " << endl;
continue;
}
result = findData(userIdGiven, dataType);
cout << "name: " << result;
}
else if (choice == "user-id")
{
cout << endl << "Enter a full name e.g. John Smith ";
char oneLine[80];
std::getline(oneLine, 80);
cout << oneLine;
}
string ans;
cout << endl << "Would you like to play again? (yes/no) " << endl;
cin >> ans;
if ( (ans == "yes") || (ans == "Yes") || (ans == "Y") || (ans == "y") )
continue;
else
break;
cin >> pause;
}
return 0;
}
【问题讨论】:
-
是否忽略了整个 else if 块?
-
将
std::getline与std::string一起使用比将std::istream::getline与char[N]一起使用要容易得多。 -
@jesus:不是,不是。第一行打印然后它只是忽略其余的并继续!快把我逼疯了
-
@KillianDS :通常这就是您想要做的,但是对于 std::string , == 运算符被重载,以便它在 C++ 中工作。此外,您确定一旦到达该语句就消耗了所有输入,因为 getline 将尝试使用任何存在的输入(如果您还没有)。
-
我没有完全记住这一点,但是是否存在一些问题,您需要在 cin 之后刷新缓冲区,或者下次输入时将上一个输入中的换行符用作输入叫它?
标签: c++ inputstream getline