在 C++ 中,getline() 不是读取字符串的所有字母,而是一个接一个地接受多个字符串

In c++ getline() is not reading all the letters of the string while accepting multiple strings one after the other

#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()

您需要做的是将 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

您在循环中调用 cin.ignore();,因此它会在每次迭代中忽略一个字符。由于您只使用 operator >> 一旦您需要将对 ignore 的调用移出循环并将其放在输入之后。

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() 消耗了你的角色。现在添加一些细节,输入基本上存储在缓冲区中(不是在重定向的情况下)。现在,当您使用 getline 时,它​​会执行此操作。

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

Extracts characters from is and stores them into str [getline(cin.str)]until the delimitation character delim is found (or the newline character, '\n', for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

所以基本上 \ngetline 本身消耗和丢弃。现在你使用 cin.ignore()

istream& ignore (streamsize n = 1, int delim = EOF); Extract and discard characters Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

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

这就是你如何获得这样的输出。