【问题标题】:My program skips a bunch of code when I include multiple arrays inside the structure当我在结构中包含多个数组时,我的程序跳过了一堆代码
【发布时间】:2019-10-18 02:17:25
【问题描述】:

我正在尝试学习 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;
}

在我输入名字后,代码会输出信息。为什么会这样做,我怎样才能让它以第二种方式工作?

【问题讨论】:

    标签: c++ arrays struct


    【解决方案1】:

    发生这种情况是因为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();
    

    【讨论】:

    • 输入之间是什么意思?
    • 什么是 mac 替代品,因为我在 Xcode 中编码?
    • 对于 getch() 你必须包含 conio.h 头文件。如果您使用的是 C++ 12 或更高版本,则可以使用 getchar() 或 cin.get()
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多