C++ Getline忽略输入的第一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17006401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:49:22  来源:igfitidea点击:

Getline ignoring first character of input

c++arrays

提问by lisovaccaro

I'm just starting with arrays in C++ and I'm having a problem getting the first character of an array.

我刚开始使用 C++ 中的数组,但在获取数组的第一个字符时遇到了问题。

This is my code,

这是我的代码

1- I enter a name, such as "Jim"

1- 我输入一个名字,例如“Jim”

char name[30];
cin.ignore();
cin.getline(name, 30);

2- Right away I try to cout the array

2-我立即尝试计算数组

    cout<<"NAME:"<<name; // THIS PRINTS 'im'

I was sure it would print 'J'. What am I doing wrong?

我确信它会打印“J”。我究竟做错了什么?

回答by Amit

Here is signature of cin.ignore:

这是cin.ignore的签名:

istream& ignore (streamsize n = 1, int delim = EOF);

So if you call ignore function without any parameters, it will ignore '1' char by default from input. In this case it ignored 'J'. Remove ignore call and you will get 'Jim'.

因此,如果您在不带任何参数的情况下调用 ignore 函数,默认情况下它会从输入中忽略 '1' 字符。在这种情况下,它忽略了“J”。删除忽略电话,你会得到“吉姆”。

回答by someone

Just remove cin.ignore();

只需删除 cin.ignore();

This ignores the first character, thus you miss the 'J'.

这会忽略第一个字符,因此您会错过 'J'。

回答by gengiskanhg

I had this piece of code with the problem that it was eating the first character after the first cycle (first cycle was ok)

我有这段代码的问题是它在第一个周期后吃掉了第一个字符(第一个周期没问题)

do{
    cout << endl << "command:> ";
    string cmdStr1="";
    cin.ignore();
    getline(cin, cmdStr1);
    cout << "cin= " << cmdStr1 << endl; //For Debuging
    //...more code here
}while(1);

Output was:

输出是:

command:> pos

命令:> pos

cin= pos

cin= pos

command:> pos ... from 2nd loop it started to delete the 1st character

命令:> pos ... 从第二个循环开始删除第一个字符

cin= os

cin= os

...

...

If "cin.ignore();" was commented then it resulted in a "segmentation fault":

如果“cin.ignore();” 被评论然后它导致了“分段错误”:

command:> cin=

命令:> cin=

Segmentation fault

分段故障

Solution working for me:

对我有用的解决方案:

To move the "cin.ignore();" line just before the do-while loop.

移动“cin.ignore();” 在 do-while 循环之前的行。

cin.ignore();

      do{
            std::cout << endl << "command:> ";
            std::string cmdStr1="";
            std::getline(std::cin, cmdStr1);
            std::cout << "cin= " << cmdStr1 << endl; //For Debuging
            //...more code here
    }while(1);

Output was:

输出是:

command:> pos

命令:> pos

cin= pos

cin= pos

command:> pos

命令:> pos

cin= pos

cin= pos

...

...

...

...

P.S. It was incredible hard to put code here... I am disappointment to continue collaborating.

PS 把代码放在这里真是太难了……我对继续合作感到失望。