C++ 字符输入仅输出第一个字母

c++ character input only first letter being output

本文关键字:第一个 输出 字符输入 C++      更新时间:2023-10-16

>我是 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;
}
}

提前谢谢你

您的问题出在数据上:

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

char name[20];是一个数组,您可以在其中存储 20 个字符,因此您的程序将存储 1char、1int和 1doublestudentid

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

------编辑-----

我看到你是 c++ 的新手,所以向量对你来说可能有点高级,所以你可以按照评论中提到的方法。studentid studen[20];制作一个这样的结构数组,并将结构更改为:

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

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

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

你可以去

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

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

相关文章: