试图在getline中使用int

Sco*_*ott 4 c++ string int getline

cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
getline(cin, totalquestions);
Run Code Online (Sandbox Code Playgroud)

这段小代码来自我创建的类中的一个函数,我需要totalquestions成为一个int,以便它可以运行for循环并不断询问我提出的问题总数.

question q;
for(int i = 0; i < totalquestions; i++)
{
    q.inputdata();
    questions.push_back(q);
}
Run Code Online (Sandbox Code Playgroud)

这段代码在哪里发挥?有没有人有任何想法让这项工作?

seh*_*ehe 12

使用

cin >> totalquestions;
Run Code Online (Sandbox Code Playgroud)

检查错误

if (!(cin >> totalquestions))
{
    // handle error
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*nze 5

getline将整行作为字符串读取。您仍然需要将其转换为 int:

std::string line;
if ( !std::getline( std::cin, line ) ) {
//  Error reading number of questions...
}
std::istringstream tmp( line );
tmp >> totalquestions >> std::ws;
if ( !tmp ) {
//  Error: input not an int...
} else if ( tmp.get() != EOF ) {
//  Error: unexpected garbage at end of line...
}
Run Code Online (Sandbox Code Playgroud)

注意,std::cin直接 输入totalquestions不行的;它将 '\n'在缓冲区中留下尾随字符,这将使所有后续输入不同步。可以通过添加对 的调用来避免这种情况std::cin.ignore,但这仍然会由于尾随垃圾而错过错误。如果您正在进行面向行的输入,请坚持使用getline, 并用于std::istringstream任何必要的转换。


Fre*_*Foo 0

不要使用getline

int totalquestions;
cin >> totalquestions;
Run Code Online (Sandbox Code Playgroud)