【问题标题】:In c++ getline() is not reading all the letters of the string while accepting multiple strings one after the other在 c++ 中,getline() 在一个接一个地接受多个字符串时没有读取字符串的所有字母
【发布时间】:2017-10-24 14:35:34
【问题描述】:
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t; //Number of test cases
    while(t--){
        cin.ignore();
        string s;
        getline(cin,s);
        cout<<s<<endl;
    }
    return 0;
}

输入:

2
AMbuj verma
Aaaa bBBB
Bm Chetan

输出:

AMbuj verma
aaa bBBB
m Chetan

上面的程序没有读取字符串的第一个字符。

这是我得到的输出。

我也用过cin.ignore()

【问题讨论】:

  • 这就是原因:你忽略了每一行的第一个字符
  • 不要#include ,它是一个私有的非标准头文件,不应该包含。
  • 谢谢!!我的代码运行良好。

标签: c++ string getline


【解决方案1】:

您需要做的是将cin.ignore() 放在while 循环之外,因为每次循环工作时,它都会占用字符串的第一个字母。

    cin>>t; //Number of test cases
    cin.ignore();
    while(t--){

        string s,a;
        getline(cin,s);
        cout<<s<<endl;
    }

最后,当您的代码中没有使用 string a 时,您为什么要写 string s, a

【讨论】:

  • 谢谢!!我的代码被接受了。我已经删除了字符串 a。
【解决方案2】:

您在循环中调用cin.ignore();,因此它将在每次迭代中忽略一个字符。因为您只在需要将对ignore 的调用移出循环并在输入之后使用时才使用operator &gt;&gt;

cin>>t; //Number of test cases
cin.ignore(); // get rid of newline
while(t--){
    string s,a;
    getline(cin,s);
    cout<<s<<endl;
}

【讨论】:

  • 谢谢!!我将 cin.ignore() 移到了循环之外,得到了正确的输出。
【解决方案3】:

实际上是的,cin.ignore() 会消耗你的角色。现在要详细添加一些内容,输入基本上存储在缓冲区中(不是在重定向的情况下)。现在,当您使用 getline 时,它​​会执行此操作。

(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);<--you used this

is 中提取字符并将它们存储到str [getline(cin.str)] 直到 找到分隔符 delim(或换行符,'\n', 对于 (2))。

如果在 is 中到达文件末尾或者如果 在输入操作过程中出现其他一些错误。

如果找到分隔符,则将其提取并丢弃(即 没有存储,下一个输入操作将在它之后开始)。

所以当\n 基本上被getline 自己消耗和丢弃时。现在你使用cin.ignore()

istream& 忽略 (streamsize n = 1, int delim = EOF);提取和 丢弃字符从输入序列中提取字符并 丢弃它们,直到提取了 n 个字符,或者一个 比较等于 delim。

所以你没有指定任何东西——所以它丢弃了缓冲区中可用的一个字符,它是第一个字符。 (但您认为会有 \n 被消耗,但它不存在,因为它被 getline() 丢弃。

这就是你得到这样的输出的方式。

【讨论】:

  • 感谢详细的解释!!
猜你喜欢
  • 2018-10-03
  • 2018-10-15
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2014-03-15
  • 2019-11-03
  • 2012-02-02
  • 1970-01-01
相关资源
最近更新 更多