C++ 字符输入仅输出第一个字母
c++ character input only first letter being output
>我是 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
和 1double
每studentid
如果要存储名称,则需要将名称声明为字符串的数组或向量(检查上面的代码)。
------编辑-----
我看到你是 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()。
相关文章:
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 如何输出字符串第二个单词的第一个字母?
- C++ 字符输入仅输出第一个字母
- 输出是从您输入的矩阵中打印出矩阵的转置,但我的代码只是打印出您输入的第一个矩阵
- 创建一个动态数组,包括汽车的年份和品牌,但无法保存我的第一个输出
- 集合差分的输出可以存储在第一个输入中
- 输出流中的第一个字符将替换为该流中被删除的最后一个字符.为什么会这样
- C++文件输出只接受第一个单词
- 为什么第二个程序的输出和第一个程序不同
- 为什么第一个程序不起作用,而第二个程序有效?其次,为什么输出是它给出的
- 从文件输出原始字节时,第一个字节已损坏
- 当键入指定单词作为第一个字母时显示输出,并忽略后面的其他单词
- 伪随机数生成器给出相同的第一个输出,但随后的行为和预期的一样
- 如何组合两个查询并使用第一个查询的结果作为第二个查询的输出
- C++初学者,开关不输出字符串的第一个字符
- Getline()从数组中省略输出的第一个字母
- Getline()省略输出字符串的第一个字母
- 在Visual Studio中使用本地Windows调试器运行第一个程序。输出窗口显示大量"Cannot find or open the PDB file"
- 当我为第一个字符串(C++)输入空格时,如何删除输出中的双引号和逗号
- cout标志只对第一个输出有效