【问题标题】:Program works fine under the condition I don't have a space in my input? C++ [duplicate]在我的输入中没有空格的情况下,程序可以正常工作吗? C++ [重复]
【发布时间】:2023-03-24 19:40:01
【问题描述】:

我刚开始上入门级 C++ 课程,我正在做我的第一份家庭作业。代码似乎工作得很好,除了当输入中包含一个空格时,它只是跳过输入所在行之后的其余问题。

我希望这是有道理的!

// This program prompts the user a few general questions about themselves, the date, which IDE they are using, and which machine they have downloaded the IDE on to.


#include <iostream>
#include <string>
using namespace std;

int main()
{
    string userName, currentDate, softwareName, machineName;

    //Ask the user his name.
    cout << "What is your name? ";
    cin >> userName;

    //Ask the user the date.
    cout << "What is the date? ";
    cin >> currentDate;

    //Asks the user which software he downloaded.
    cout << "What is the name the IDE software you downloaded? ";
    cin >> softwareName;

    //Asks the user which machine he downloaded his IDE on.
    cout << "Which machine did you download the IDE on? (ie. home computer, laptop, etc.) ";
    cin >> machineName;

    //Prints out the users inputs going downwards.
    cout << "" <<  userName << endl;
    cout << "" <<  currentDate << endl;
    cout << "" <<  softwareName << endl;
    cout << "" <<  machineName << endl;
    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    提取运算符 (&gt;&gt;) 将读取输入,直到出现空格或下一行(可能还有其他空白字符,但我不确定)。因此,当您输入带有空格的内容时,空格后面的部分将被解释为下一个问题的答案。要读取带空格的输入,请使用getline() 函数,默认情况下不会停止读取空格,如下所示:getline(cin, userName)。请注意,提取运算符将在输入流中保留下一行,这将导致后续的@987654324 @调用给一个空字符串。确保在提取后调用getline() 之前调用cin.ignore()。我试图尽可能简单地解释这一点,希望你能理解。

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 1970-01-01
      • 2019-01-14
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多