cin.get()的运行时错误

时间:2017-12-19 08:33:02

标签: c++

#include<iostream>
#include<string>
#include<cstring>

using namespace std;
void cpp_string();
void cstyle_string();

int main()
{
  cpp_string();
  cstyle_string();

  system("pause");
  return 0;
}

void cpp_string()
{
  string fName, lName;
  char grade;
  int age;

  cout << "What is your first name?";
  getline(cin, fName);
  cout << "What is your last name?";
  getline(cin, lName);
  cout << "What letter grade do you deserve?";
  cin >> grade;
  cout << "What is your age?";
  cin >> age;

  cout << "Name: " << fName << ", " << lName << endl;
  cout << "Grade: " << grade << endl;
  cout << "Age: " << age << endl;

  return;
}

void cstyle_string()
{
  char fNm[20], lNm[20];
  char grade;
  int age;

  cout << "What is your first name?";
  cin.get(fNm, 20).get();
  cin.clear();
  cout << "What is your last name?";
  cin.get(lNm, 20).get();
  cout << "What letter grade do you deserve?";
  cin >> grade;
  cout << "What is your age?";
  cin >> age;

  cout << "Name: " << fNm << ", " << lNm << endl;
  cout << "Grade: " << grade << endl;
  cout << "Age: " << age << endl;

  return;
}

我的输出为

What is your first name?demiurge conon  
What is your last name?no  
What letter grade do you deserve?a  
What is your age?22  
Name: demiurge conon, no  
Grade: a  
Age: 22  
What is your first name?What is your last name?What letter grade do you deserve?What is your age?Name: ,  
Grade: ╠ 
Age: -858993460 
Press any key to continue . . . 

但如果我在不同的文件中运行cstyle_string(),那么我没有得到任何错误代码完美无缺。

我想知道为什么会这样?

1 个答案:

答案 0 :(得分:1)

有两个问题。

  1. 冗余\n

  2. 状态cin

  3. cin中的最后cpp_stringcin >> age

    它将保留\n未提取。

    cstyle_string的第一个是cin.get(fNm, 20).get();

      

    如果找到,则不会从输入序列中提取分隔符,并将其作为要从流中提取的下一个字符保留在那里

    cin.get(FNm, 20)将解析\n之前的空输入,实际上流中没有可用的字符。在这种情况下,将设置failbit标志,然后所有cin >>运算符将失败。

    您只能致电cstyle_string并直接按回车,同样的事情也会发生。