试图在getline中使用int

时间:2011-04-30 20:03:54

标签: c++ string int getline

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);
}

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

5 个答案:

答案 0 :(得分:12)

使用

cin >> totalquestions;

检查错误

if (!(cin >> totalquestions))
{
    // handle error
}

答案 1 :(得分:3)

这样做:

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

Getline用于抓取chars。可以使用getline()完成,但cin更容易。

答案 2 :(得分:2)

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 必要的转换。

答案 3 :(得分:1)

请勿使用getline

int totalquestions;
cin >> totalquestions;

答案 4 :(得分:0)

从用户获取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&gt;&gt;更好n?

Actual article explaining why

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