我有一个控制台应用程序,shopuld等待用户输入字符串。它必须是getline,因为它可能包含空格。但它不会等待输入,它会跳过它并运行函数。这是我的代码:
int main()
{
vector<person> people;
bool flag = true;
int num_people = 0;
//char*filename="names.txt";
people = read_file();
while(flag)
{
int sel = 0;
string args;
cout << "1 - Sök del av personnamn" << "\n"
<< "2 - Sök städer" << "\n" << "3 - Avsluta" << endl;
cin >> sel;
if(sel == 1)
{
cout << "Mata in delen av personnamnet" << endl;
getline(cin, args);
print_result(find_in_names(people, args));
}
else if(sel == 2)
{
cout << "Mata in staden" << endl;
getline(cin, args);
args = lower_letters(args);
print_result(find_person_from_city(people, args));
}
else if(sel==3)
{
flag=false;
}
else
{
cout << "FEL, TRYCK OM!" << endl;
}
}
}
运行没有错误,它只是跳过getline并且不让用户输入任何内容。
答案 0 :(得分:4)
以下是使用getline()
函数的简单方法:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string name;
int age;
cout << "How old are you ?" << endl;
cin >> age;
cin.ignore(); // for avoiding trouble with 'name' when we're gonne use getline()
cout << "What's your name ?" << endl;
getline(cin, name);
system("PAUSE");
}
不要忘了,如果你使用cin
befor getline()
,你必须把这行:
cin.ignore();
所以你的代码应该是这样的:
int main()
{
vector<person> people;
bool flag = true;
int num_people = 0;
//char*filename="names.txt";
people = read_file();
while(flag)
{
int sel = 0;
string args;
cout << "1 - Sök del av personnamn" << "\n" << "2 - Sök städer" << "\n" << "3 - Avsluta" << endl;
cin >> sel;
cin.ignore()
if(sel == 1)
{
cout << "Mata in delen av personnamnet" << endl;
getline(cin, args);
print_result(find_in_names(people, args));
}
else if(sel == 2)
{
cout << "Mata in staden" << endl;
getline(cin, args);
args = lower_letters(args);
print_result(find_person_from_city(people, args));
}
else if(sel==3)
{
flag=false;
}
else
{
cout << "FEL, TRYCK OM!" << endl;
}
}
}
这是一些文档http://www.cplusplus.com/reference/istream/istream/ignore/,希望它会有所帮助;