我正在尝试学习C++结构。当我像这样运行我的代码时:
#include<iostream>
using namespace std;
struct person{
char firstName[50];
int age;
float gradYear;
};
int main(){
person p1;
cout << "Whats your FIRST name?";
cin.get(p1.firstName, 50);
cout << "Whats your AGE?";
cin >> p1.age;
cout << "Whats your GRADUATION YEAR?";
cin >> p1.gradYear;
cout << "Displaying Your Information . . . " << endl;
cout << "First Name: " << p1.firstName << endl;
cout << "Age: " << p1.age << endl;
cout << "Graduation Year: " << p1.age << endl;
return 0;
}
代码按照我想要的方式工作,但是当我像这样运行代码时:
#include<iostream>
using namespace std;
struct person{
char firstName[50];
char lastName[50];
int age;
char branch[50];
float gradYear;
};
int main(){
person p1;
cout << "Whats your FIRST name?";
cin.get(p1.firstName, 50);
cout << "Whats your LAST name?";
cin.get(p1.lastName, 50);
cout << "Whats your AGE?";
cin >> p1.age;
cout << "Are you Corps or Civilian?";
cin >> p1.branch;
cout << "Whats your GRADUATION YEAR?";
cin >> p1.gradYear;
cout << "Displaying Your Information . . . " << endl;
cout << "First Name: " << p1.firstName << endl;
cout << "Last Name: " << p1.lastName << endl;
cout << "Age: " << p1.age << endl;
cout << "Branch: " << p1.branch << endl;
cout << "Graduation Year: " << p1.age << endl;
return 0;
}
代码在我输入名字后输出信息。它为什么要这样做,我怎样才能让它以第二种方式工作?
发生这种情况是因为cin.get()
方法输入名字,当您按回车键时,输入将输入到所有其他输入中。 这是一个意想不到的行为...
您可以通过在输入之间写入getch()
来克服此问题。
我的意思
是..cout << "Whats your FIRST name?";
cin.get(p1.firstName, 50);
getch();
cout << "Whats your LAST name?";
cin.get(p1.lastName, 50);
getch();
cout << "Whats your AGE?";
cin >> p1.age;
getch();
cout << "Are you Corps or Civilian?";
cin >> p1.branch;
getch();
cout << "Whats your GRADUATION YEAR?";
cin >> p1.gradYear;
getch();