【问题标题】:Just started coding C++ [duplicate]刚开始编写 C++ [重复]
【发布时间】:2019-07-24 02:52:09
【问题描述】:

我的代码中似乎有什么问题?

当我输入年龄后按Enter时,提示已经结束,无需询问我的地址。我知道我可以使用getline() 作为年龄,但如果用户输入非整数答案怎么办?

抱歉,我昨天刚开始编码,我想学习基础知识。

#include <iostream>

using namespace std;

int main()
{
    int age;
    string name, address;

    cout << "Please enter the name of the user:" << endl;
    getline(cin, name);

    cout << "Please enter age of the user:" << endl;
    cin >> age;

    cout << "Please enter the address of the user:" << endl;
    getline(cin, address);

    cout << "Your name is " << name << " and you are " << age 
     << " years old " << " who lives in " << address << endl;

    cout << "Thank you for using my program!";


    return 0;
}

【问题讨论】:

  • 您将getlinecin &gt;&gt; whatever 通话混在一起。这通常会导致疯狂。
  • getline 从输入流中提取'\n'cin 没有。在cin 之后,'\n' 仍保留在输入流中,并且由于getline 只读取直到遇到'\n',它什么也不读取并且似乎跳到第二个getline 提示符。
  • 首先看看为什么要使用两种不同的输入方式:getline(cin, ) 和 cin>>?如果你能回答这个问题,你就会得到你的问题的答案。所以只要看看 getline 的文档就知道它和 cin 有什么不同了>>
  • 您的问题已由上述副本回答。但是,作为这里的新用户,请使用tour 并阅读How to Ask
  • this answer我今天早些时候发布的另一个问题,它也可以应用于这个问题。

标签: c++


【解决方案1】:

只需在 'cin>>age' 之后添加 'cin.ignore()',如下所示:

cout << "Please enter age of the user:" << endl;
cin >> age;
cin.ignore();
cout << "Please enter the address of the user:" << endl;
getline(cin, address);

当 getline() 读取输入时,输入流中会留下一个换行符,因此它不会读取程序中的字符串(地址)。

如果用户在年龄中输入“float”或“double”等而不是“int”,那么它将简单地从中提取整数, 例如: 如果用户输入 39.29 或 39.00005 或 39.00 或然后 age=39

To know more about getline check the following link:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2011-05-06
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多