#include<iostream> using namespace std; struct mystruct { char *name; int age; char *sex; char *address; }; main() { int i; mystruct s1; char x[10]={NULL}; char y[10]={NULL}; char z[20]={NULL}; cout << "输入姓名:"; while ((cin.get()!="\n")&&(i<10)) { cin >> x[i]; i++; } cout << "输入性别:"; while ((cin.get()!="\n")&&(i<10)) { cin >> y[i]; i++; } cout << "输入地址:" ; while ((cin.get()!="\n")&&(i<20)) { cin >> z[i]; i++; } cout << "输入年龄:" ; cin >> s1.age; cout << "***************************" << endl; cout << "输入信息为:" << endl; s1.name=x; s1.sex=y; s1.address=z; cout << s1.name << "年龄为:" << s1.age << "性别为:" << s1.sex << "地址为:" << s1.address << endl; }
想要通过键盘输入结构体中各个数组元素,然后输出,通过回车键控制结束输入并转到下一数组的输入,但是总是得不到预想的结果,结果如下:
当输入完姓名之后敲回车,程序就结束运行,不能转到下一个数组的输入。求前辈们解答。
解决方案
10
cin.get() 取走一个字符, cin >> x[i] 再取走一个字符, 莫非你是要间隔一个取一个吗?
60
1.你应该用一个char变量接收cin.get()得到的字符,然后赋值给对应的字符数组
2.你每次读取之前应该将i重新置为0
2.你每次读取之前应该将i重新置为0
#include<iostream> using namespace std; struct mystruct { char *name; int age; char *sex; char *address; }; void main() { int i = 0; mystruct s1; char x[10] = { NULL }; char y[10] = { NULL }; char z[20] = { NULL }; cout << "输入姓名:"; char ch; while ((ch = cin.get()) != "\n" && (i<10)) { x[i] = ch; i++; } cout << "输入性别:"; i = 0; while ((ch = cin.get()) != "\n" && (i<10)) { y[i] = ch; i++; } cout << "输入地址:"; i = 0; while ((ch = cin.get()) != "\n" && (i<20)) { z[i] = ch; i++; } cout << "输入年龄:"; cin >> s1.age; cout << "***************************" << endl; cout << "输入信息为:" << endl; s1.name = x; s1.sex = y; s1.address = z; cout << s1.name << "年龄为:" << s1.age << "性别为:" << s1.sex << "地址为:" << s1.address << endl; }