Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::getline(),而循环内容未运行 目标_C++_Loops_While Loop_G++_Std - Fatal编程技术网

C++ std::getline(),而循环内容未运行 目标

C++ std::getline(),而循环内容未运行 目标,c++,loops,while-loop,g++,std,C++,Loops,While Loop,G++,Std,新的C++,在其他任何地方都没有找到一个明确的答案。我正在开发一个简单的程序,从控制台中读取用户输入的消息。这是一个使用字符串变量/连接的练习 我需要创建读取用户输入的循环,其中可能包含来自命令shell的多行输入 因此,我的函数需要读取该输入,同时忽略换行符,并在用户在新行上输入两个“&&”时结束 企图 这是我的函数: string get_message() { string message, line; cout << "Enter the message &


新的C++,在其他任何地方都没有找到一个明确的答案。我正在开发一个简单的程序,从控制台中读取用户输入的消息。这是一个使用字符串变量/连接的练习

我需要创建读取用户输入的循环,其中可能包含来自命令shell的多行输入

因此,我的函数需要读取该输入,同时忽略换行符,并在用户在新行上输入两个“&&”时结束

企图
这是我的函数:

string get_message() {
    string message, line;
    cout << "Enter the message > ";
    cin.ignore(256, '\n');
    while (getline(cin, line) && line != "&&") {
        message = message + " " + line;
        cout << message;
        cin.clear();
    }
    return message;
}
问题:
  • 什么时候调用循环内容
  • 为什么我只得到上一行,而不是所有以前(假定)连接的行
  • 有没有更好的编码方法
    • 将其分解:

      string get_message() {
          string message, line;
          cout << "Enter the message > ";
      
      丢弃第一行或256个字符,以先到者为准。可能不是你想做的。从思想上讲,如果您认为流中可能已经有垃圾,请在调用函数之前清空流。不管怎么说,这肯定是OP问题的一部分

          while (getline(cin, line) && line != "&&") {
      
              cin.clear();
      
      成功获取一行时,该行不是“&&”。看起来不错。注意:新行被getline函数剥离,因为它们是令牌分隔符,将它们保留在返回的令牌中或保留在流中只会导致问题

              message = message + " " + line;
      
      将行追加到消息

              cout << message;
      
      清除cin上的错误条件。不需要。如果cin处于错误状态,则while循环不会进入

          }
          return message;
      }
      

      普通的东西。此处没有显示内容,但如果程序在此点后不久结束,则调用
      cout.flush()
      ,将
      std::flush
      发送到cout,或者有一个
      cout“循环内容似乎没有运行”—它肯定会运行。您在哪里打印
      消息
      ?在循环(已编辑)中,您意识到
      cin.ignore(256,'\n')
      正在吃掉你的第一个输入行,对吗?你认为这有什么作用?请注意,我不明白为什么两行被忽略。忽略一行输入的正确方法是
      cin.ignore(numeric_limits::max(),'\n')我真的很感谢你的回答!肯定有助于澄清问题
      
              cin.clear();
      
          }
          return message;
      }
      
      Messages.. this is a new message.
      
      I'm a message on a new line, look at me.
      
      New line.
      
      &&
      
      I'm a message on a new line, look at me. I'm a message on a new line, look at me. New line.
      
       I'm a message on a new line, look at me. New line.