【问题标题】:How do I make cin accept spaces? [duplicate]如何让 cin 接受空格? [复制]
【发布时间】:2014-11-20 22:56:57
【问题描述】:

我希望代码能够在我输入姓名时接受全名。如何让 cin 接受空格?

当我输入一个带空格的名字时,结果是它假定下一个输入的主题名是姓氏。我该如何解决这个问题?

#include<iostream>
using namespace std;

int main()
{
    float mark1, mark2, mark3, mark4;
    char subject1[25], subject2[25], subject3[25], subject4[25];
    char name;
    float average;

    cout << "Please enter your name"<< endl;
    cin >> name;

    cout << "Please enter the first subject name"<< endl;
    cin >> subject1;

    cout << "Please enter the mark for " <<subject1<< endl;
    cin >>mark1;

    cout << "Please enter the second subject name"<< endl;
    cin >> subject2;

    cout << "Please enter the mark for " <<subject2<< endl;
    cin >>mark2;

    cout << "Please enter the third subject name"<< endl;
    cin >> subject3;

    cout << "Please enter the mark for " <<subject3<< endl;
    cin >>mark3;

    cout << "Please enter the fourth subject name"<< endl;
    cin >> subject4;

    cout << "Please enter the mark for " <<subject4<< endl;
    cin >>mark4;

    average=(mark1+mark2+mark3+mark4) / 4;

    cout << name << "'s " << subject1<< " mark is " <<mark1 <<", " << subject2<< " mark is " << mark2 <<", " <<subject3 <<" mark is " <<mark3 <<", " <<subject4<< " mark is " <<mark4 <<". His/her average is " <<average<< endl;

    cout << endl;

    system("PAUSE");
    return 0;
}

【问题讨论】:

    标签: c++ cin


    【解决方案1】:

    尝试使用getline(cin, &lt;variable name&gt;)

    例如:

    string name;
    getline(cin, name);
    cout << name;
    

    请务必阅读有关使用 getline 的信息: getline reference

    【讨论】:

      猜你喜欢
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2016-12-03
      • 2018-10-26
      • 2015-04-10
      • 1970-01-01
      相关资源
      最近更新 更多