C++ cin 在点击回车后没有返回

C++ cin not returning after hitting enter

所以我希望能够输入如下内容: '6, -15, 12, 44, ...' 等等。并将这些整数添加到向量中。 但是,当我输入上述输入并按回车键时,它什么也没做。如果我然后输入一个字母并按回车键,然后输入另一个字母并按回车键,它最终会 returns 所需的结果。 如果我输入更多数字并按回车键,它将继续 return 什么都没有。 有人可以指出我这里出了什么问题的正确方向吗?谢谢你们。我希望我对这个问题的解释是有道理的。

int main()
{

// The user inputs a string of numbers (e.g. "6, 4, -2, 88, ..etc") and those integers are then put into a vector named 'vec'.
std::vector<int> vec;

int value;
std::cin >> value;

if ( std::cin ) 
{

    vec.push_back( value );
    char separator;

    while ( std::cin >> separator >> value ) 
    {
        vec.push_back( value );
    }

}

std::cout << vec.size() << std::endl;
for ( int i = 0; i < vec.size(); i++ )
{
    std::cout << vec.at(i) << ' ';
}
std::cout << std::endl;
}

想想你的程序解析你的输入的方式。首先,您总是在每个数字后都需要一个逗号,您是否需要在输入的末尾使用它?二、你认为你的阅读失败是如何结束循环的?

这就是为什么你需要输入两个字符,一个作为末尾的分隔符,第二个使整数读取失败。

However when I enter said input and press enter it does nothing.

这是对程序功能的错误解释。向您的程序添加一些调试输出,您会注意到该程序正在处理您的输入。

while ( std::cin >> separator >> value ) 
{
    std::cout << "Read separator: " << separator << std::endl;
    std::cout << "Read value: " << value << std::endl;

    vec.push_back( value );
}

If I then enter a letter and press enter, then enter another letter and press enter, it finally returns the desired result.

您似乎希望程序在您输入一行文本后停止读取输入。

如果您编写了程序,当您按 Enter 时,while 循环不会停止。它等待下一行的额外输入。

通过输入字母,您已经为 separator 提供了输入。通过输入另一个字母,您已将 std::cin 置于错误状态。那是 while 循环中断的时候。

在我看来,您真正要找的是:

  1. 阅读一行文字。您可以为此使用 std::getline
  2. 从文本行中读取数字。您可以为此使用 std::istringstream
  3. 输出数据。

int main()
{
   // The user inputs a string of numbers (e.g. "6, 4, -2, 88, ..etc") and those integers are then put into a vector named 'vec'.
   std::vector<int> vec;

   std::string line;
   if ( getline(std::cin, line) )
   {
      std::istringstream str(line);

      int value;
      str >> value;
      vec.push_back( value );
      char separator;
      while ( str >> separator >> value ) 
      {
         vec.push_back( value );
      }
   }

   std::cout << vec.size() << std::endl;
   for ( int i = 0; i < vec.size(); i++ )
   {
      std::cout << vec.at(i) << ' ';
   }
   std::cout << std::endl;
}