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

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

question q;
for(int i = 0; i < totalquestions; i++)
{
    q.inputdata();
    questions.push_back(q);
}

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

4

5 回答 5

12

利用

cin >> totalquestions;

也检查错误

if (!(cin >> totalquestions))
{
    // handle error
}
于 2011-04-30T20:06:08.397 回答
3

做这个:

int totalquestions;
cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
cin >> totalquestions;

Getline 是用来抓取的chars。它可以用 来完成getline(),但cin要容易得多。

于 2011-04-30T20:05:53.560 回答
3

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...
}

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

于 2011-04-30T23:48:26.457 回答
1

不要使用getline

int totalquestions;
cin >> totalquestions;
于 2011-04-30T20:05:34.613 回答
1

从用户那里获取 int 的更好方法之一:-

#include<iostream>
#include<sstream>

int main(){
    std::stringstream ss;

    ss.clear();
    ss.str("");

    std::string input = "";

    int n;

    while (true){
        if (!getline(cin, input))
            return -1;

        ss.str(input);

        if (ss >> n)
            break;

        std::cout << "Invalid number, please try again" << std::endl;

        ss.clear();
        ss.str("");
        input.clear();
}

为什么它比使用 cin >> n 更好?

解释原因的实际文章

至于您的问题,请使用上面的代码获取 int 值,然后在循环中使用它。

于 2015-11-25T15:34:04.490 回答