【问题标题】:CodeBlocks string output delimiteredCodeBlocks 字符串输出分隔
【发布时间】:2017-12-16 16:20:23
【问题描述】:

我正在测试 CodeBlocks 中程序的字符串输出。这是代码:

    #include <iostream>
    #include <string>
    using namespace std;

    int main(){

    string entry = "";
    while(entry!="x"){

        cout<<"Enter: "; 
        cin>>entry;
        cout<<entry.substr(0,1)<<endl;

    }
    return 0;
}

但是打印结果好像它被空格和 cout 字符串 "Enter" 以错误的顺序分隔,就好像它被窃听一样。可能是什么原因,我该如何解决这种情况?

Output:

Enter: P q r
P
Enter: q
Enter: r
Enter: 

【问题讨论】:

  • &gt;&gt; 运算符提取空格分隔的内容。有好书清单here.
  • 这就是流式输入的正常工作方式。您可能想在 std::string 中使用getline

标签: c++ string output codeblocks


【解决方案1】:

要阅读整行,不要使用cin &gt;&gt; whatever。当遇到空格(空格、制表符和换行符)时,它将停止读取。使用std::getline()

getline(cin, entry);

现在这成为了现实:

assert(entry == "P q r");

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 2011-06-27
    相关资源
    最近更新 更多