尝试在 getline 中使用 int

Trying to use int in getline

本文关键字:int getline      更新时间:2023-10-16
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);
}

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

使用

cin >> totalquestions;

也检查错误

if (!(cin >> totalquestions))
{
    // handle error
}
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进行任何必要的转换。

这样做:

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

Getline是为了抢chars。它可以用getline()来完成,但cin要容易得多。

从用户那里获取 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值,然后在循环中使用它。

不要使用 getline

int totalquestions;
cin >> totalquestions;