c ++字符输入只输出第一个字母

时间:2017-11-22 09:52:56

标签: c++

我是c ++的新手,我不知道为什么它只是在字符输入中输出的第一个字母,即使我在其上键入10个字符。

#include<iostream>

using namespace std;
struct studentid
{
    char name[20];
    int age[20];
    double salary[20];

};

int main(){
    int num;
    studentid student;
    cout<<"Enter Number of Student: ";
    cin>>num;
    cout<<"======================" <<endl;

    for(int x=0;x<num;x++){
        cout<<"Student " <<x+1 <<endl;
        cout<<"Enter name: ";
        cin>>student.name[x];
        cin.ignore(1000,'\n');
        cout<<"Enter age: ";
        cin>>student.age[x];
        cout<<"Enter salary: ";
        cin>>student.salary[x];

    }
    for(int x =0;x<num;x++){
        cout<<"========================" <<endl;
        cout<<"Student name: " <<student.name[x] <<endl <<"Student age: "<<student.age[x] <<endl <<"Student salary: "<<student.salary[x] <<endl;
    }
}

提前谢谢

2 个答案:

答案 0 :(得分:0)

您的问题出在数据上:

struct studentid
{
    char name[20];---> //change this for std::vector<string> name
    int age[20];
    double salary[20];

};

char name[20];是一个数组,您可以存储20个字符,因此您的程序将按char <存储1 int,1 double和1 studentid < / p>

如果要存储名称,则需要将name声明为数组或字符串向量(请查看上面的代码)。

------ ----- EDIT

我发现你是c ++的新手,所以矢量对你来说有点先进水平,所以你可以按照评论中提到的方法。创建一个像studentid studen[20];这样的结构数组,并将结构更改为:

struct studentid
{
    char name[20];
    int age;
    double salary;

};

但请注意,名称不得超过19个字符,并确保将最后一个字符设置为NULL

答案 1 :(得分:0)

你真的不需要使用一系列字符。使用一个字符串,它将像一个字符数组一样工作。您当前代码的问题是cin只能在输入之前获取所有内容,因此当您键入第一个字符并按下Enter按钮时,您将终止cin。相反,你应该使用不以enter结尾的getline()。

你可以选择

      #include "string"
      string name;
      getline(cin, name);

或在当前代码中使用getline()。

相关问题