简体   繁体   English

Getline 总是忽略输入的第一个字 c++

[英]Getline always ignoring first word of input c++

I'm having trouble with this code.我在使用这段代码时遇到了问题。 I want it to take 2 words and it's always ignoring the first word and then taking the 2nd word.我希望它包含 2 个单词,但它总是忽略第一个单词然后使用第二个单词。 If I put in 3 words, it works perfectly and picks up the final 2 words.如果我输入 3 个词,它会完美地工作并拾取最后的 2 个词。 The prompt for this is these bullet points.对此的提示是这些要点。

  • Prompt the user to enter his/her first and last name.提示用户输入他/她的名字和姓氏。
  • Read the name from the keyboard using the getline method and store it into a variable called fullName (you will need to declare any variables you use).使用 getline 方法从键盘读取名称并将其存储到名为 fullName 的变量中(您需要声明您使用的任何变量)。
  • Print out the fullName.打印出全名。
  • Compile, debug, and run, using your name as test data.编译、调试和运行,使用您的名字作为测试数据。
  • Since we are adding on to the same program, each time we run the program we will get the output from the previous tasks before the output of the current task.由于我们正在添加到同一个程序,每次运行该程序时,我们都会在当前任务的 output 之前从先前的任务中获取 output。

How do you make this work correctly?你如何使它正常工作?

string fullName;
cout << "What is your full name" << endl;
    cin >> fullName;
getline(cin, fullName);
    cout << fullName << endl;
cout << endl;
cin >> fullName;

reads the first word of the full name.读取全名的第一个单词。

getline(cin, fullName);

reads the rest of the name over top of the first word .在第一个单词之上读取名称的 rest。 Computer programs do exactly what you tell them to do and show somewhat less than zero mercy if that's the wrong thing to do.计算机程序完全按照您的指示进行操作,如果这是错误的做法,则不会表现出零怜悯。

So given John Jacob Jingleheimer Schmidt所以给定约翰·雅各布·金格海默·施密特

cin >> fullName; // reads John into fullname
getline(cin, fullName); // reads  Jacob Jingleheimer Schmidt into fullname, 
                        // replacing John
cout << fullName << endl; // prints  Jacob Jingleheimer Schmidt

Solution解决方案

Remove the cin >> fullName;删除cin >> fullName;

getline(cin, fullName); // reads John Jacob Jingleheimer Schmidt into fullname, 
cout << fullName << endl; // prints John Jacob Jingleheimer Schmidt

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

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