使用getline可以减少字符串长度

String length getting reduced by using getline?

本文关键字:字符串 getline 使用      更新时间:2023-10-16

我正在使用getline并忽略,但有些东西工作不正常,下面是示例代码,我无法理解它是如何工作的。

int main()
{
    string str;
    int t,length;
    cin>>t;  // t is the number of test cases
    while(t--!=0)
    {
        cin.ignore();
        getline(cin,str);
        length=str.size();
        cout<<"length="<<length;
    }
}

样本输出:

2
hey hi
length 6
hey hi 
length 5

为什么长度在减少?这是因为getline和ignore函数吗?如有任何帮助,我们将不胜感激。

它给出不同长度的原因是因为ignore()函数只忽略一个字符。第一次它会忽略您在输入数字后按下的return键。但是std::getline()为您删除了return字符。因此,第二次循环ignore()会删除字符串的第一个字母,使其成为"eh hi"

int main()
{
    string str;
    int t, length;
    cin >> t;  // does not remove the RETURN character
    while(t-- != 0)
    {
        // first removed RETURN character after removes first letter
        cin.ignore(); 
        getline(cin, str);
        length = str.size();
        cout << "length = " << length;
    }
}

请尝试使用此选项:

int main()
{
    string str;
    int t, length;
    cin >> t;  // does not remove the RETURN character
    while(t-- != 0)
    {
//        cin.ignore(); // dont do this here please
        // cin >> ws skips all whitespace characters
        // including the return character
        getline(cin >> ws, str); 
        length = str.size();
        cout << " length = " << length;
    }
}

或者(也许更好)您可以将ignore()函数从循环中移到真正需要t的地方:

#include <limits>
int main()
{
    string str;
    int t, length;
    cin >> t;  // does not remove the RETURN character
    // ignore as many characters as necessary including the return
    cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    while(t-- != 0)
    {
        // cin.ignore(); // not here
        getline(cin, str);
        length = str.size();
        cout << " length = " << length;
    }
}

cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');看起来很复杂,但它是确保删除任何伪字符(如空格)的唯一方法。如果你愿意的话,你可能只需要cin.ignore()就可以进行锻炼。

阅读std::istream::ignore()

cin.ignore()默认忽略一个字符。

如果您每次都输出字符串,您会发现在以后的情况下,字符串等于"ey-hi"。h正在被丢弃。

cin持有的字符串的值在传递给getline之前会丢弃其第一个字符。

由于您使用的是getline,您可以简单地从循环中删除cin.ignore(),您的程序应该可以按预期工作。

但是,您也应该更改cin>>t;行。在这种情况下,ignore()在输入值2之后丢弃行返回。这里的stringstream允许使用getline(...)函数,或者您可以使用cin.ignore(str.max_size(), 'n');

stringstream的情况下,您的代码将变为:

#include <sstream>  // stringstream
#include <string>   // std::string
#include <iostream> // cin
int main()
{
    string str;
    int t,length;
    getline(cin, str);
    std::stringstream stream;
    stream << str;
    if (!(stream >> t)) {
        // Couldn't process to int
    }
    // cin>>t;  // t is the number of test cases
    // No longer need this line.
    while(t--!=0)
    {
        // cin.ignore(); Drop this too
        getline(cin,str);
        length=str.size();
        cout<<"length="<<length;
    }
}

如果您对空白不感兴趣,然后使用getline(cin >> ws, str)