简体   繁体   English

getline 忽略字符串输入的第一个字符

[英]getline ignores first character of string input

Why does C++'s getline function ignore the first character of my input?为什么 C++ 的getline函数会忽略我输入的第一个字符?

In this post , the culprit was cin.ignore() , but I don't have the cin.ignore() function in my code.这篇文章中,罪魁祸首是cin.ignore() ,但我的代码中没有cin.ignore()函数。

Here's a very basic sample of what I'm trying to do:这是我正在尝试做的一个非常基本的示例:

#include <iostream>
#include <string>

using namespace std;

int main(){

    string user_input;

    cout << "input: ";
    cin >> user_input;
    getline(cin,user_input);

    cout << "length: " << user_input.length() << endl;
    cout << "your input: " << user_input << endl;

    return 0;
}

The problem is, the output is totally wrong:问题是,输出是完全错误的:

input: 1 2 3
length: 4
your input:  2 3

Obviously the length of the string, with spaces included, should be 5 , not 4 .显然,字符串的长度(包括空格)应该是5 ,而不是4 You can also see that the 1st character of user_input is missing.您还可以看到user_input的第一个字符丢失了。

Can somebody explain to me why this code gives the wrong output and what I need to do to fix this problem?有人可以向我解释为什么这段代码给出了错误的输出以及我需要做什么来解决这个问题吗? I've never worked with strings that contain spaces like this.我从来没有使用过包含这样空格的字符串。 I'm curious about what causes this problem to arise: :)我很好奇是什么原因导致出现这个问题::)

cin >> user_input is the culprit. cin >> user_input是罪魁祸首。 It's grabbing the input until the first space Get rid of that line of code and you should be all set with just the getline(cin,user_input) . 它抓住输入直到第一个空格去除那行代码,你应该只使用getline(cin,user_input)

cin >> user_input;

I'm not sure why you put that line there, but that reads and consumes the first space delimited string from cin . 我不确定你为什么把那条线放在那里,但是它会读取并消耗cin第一个以空格分隔的字符串。 So it reads the 1. After that, getline reads the rest of the line, which is " 2 3" . 所以它读取1.之后, getline读取该行的其余部分,即" 2 3"

cin >> user_input; is eating the first number. 正在吃第一个号码。 Then getline() comes along and gets the rest of the input. 然后getline()出现并获得其余的输入。 Remove cin >> user_input; 删除cin >> user_input; and it should work fine. 它应该工作正常。

just remove this line cin >> user_input;只需删除这一行cin >> user_input; then your code will work.那么您的代码将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM