【问题标题】:Trying to use int in getline尝试在 getline 中使用 int
【发布时间】:2011-08-16 04:53:04
【问题描述】:
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);
}

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

【问题讨论】:

  • 请说明您认为不起作用的功能。
  • @ulidtko,实际上,对于这个问题,很容易看出什么不起作用......

标签: c++ string int getline


【解决方案1】:

使用

cin >> totalquestions;

也检查错误

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

【讨论】:

【解决方案2】:

这样做:

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

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

【讨论】:

    【解决方案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 必要的转换。

    【讨论】:

      【解决方案4】:

      不要使用getline:

      int totalquestions;
      cin >> totalquestions;
      

      【讨论】:

        【解决方案5】:

        从用户那里获取 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 更好?

        Actual article explaining why

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-12
          • 2021-05-17
          • 2011-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-31
          • 2013-03-03
          相关资源
          最近更新 更多