【问题标题】:I am getting wrong output in my cpp program我的 cpp 程序输出错误
【发布时间】:2020-08-31 19:13:11
【问题描述】:
 while(t--){
    string str, token, dummy;
    cin.ignore();
    getline(cin ,str);
    int pos = str.find(' ');
    token = str.substr(pos+1);
    str = str.substr(0, 3);
    cout << str << " " <<  token << endl;
}

在提供输入时:
添加黑客等级
添加黑客
查找 hac
找哈克

输出为:
添加黑客等级
dd 黑客
工业技术
工业界

我缺少第二行输入的第一个字符。

【问题讨论】:

  • 这看起来像英文,但我读的越多,我和低地球轨道之间的距离就越大。

标签: c++ string getline substr


【解决方案1】:

来自 istream ignore() [强调添加]

basic_istream& 忽略(std::streamsize count = 1, int_type delim = Traits::eof());

从输入流中提取和丢弃字符,直到并包括 delim。

count 的默认值为1。因此,当您在没有任何参数的情况下调用它时,它会忽略输入流中的 1 字符。

您正在观察这种忽略 second 行输入的第一个字符的行为,因为您可能在 while 循环之前给出了一些输入值(可能是 t 的输入值,如下所示 - cin &gt;&gt; t) 并点击 Enter 按钮,这会将流浪 \n 留在输入流中。第一次执行cin.ignore() 吃掉输入流中的那个流浪\n 字符,然后从第二个输入字符串开始吃掉输入的第一个字符。

要解决这个问题,您可以在进入while循环之前的输入值之后添加cin.get(),并从循环体中删除cin.ignore()

【讨论】:

  • 非常感谢您提供如此及时的反馈和清晰的解释。这意味着很多。我的问题解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多