存储字符数组值错误(c++)

Store char array value error(c++)

本文关键字:c++ 错误 字符 数组 存储      更新时间:2023-10-16

我试图使c++程序管理学生名单,但从一开始就进入错误。下面是我的程序:

#include<iostream>
#include<string.h>
using namespace std;
struct  Candidate
{
  char id[5];
char fullname[30];
int reading, listening,total;
};
int main ()
{
struct Candidate can[100];
int n=0;
do {
    cout << "Input number of candidate:";
    cin >> n;
    if (n <= 0 || n>=50)
        cout << "Candidate number must be between 0 and 50:n";
} while (n <= 0 || n>=50);
for (int i = 0; i < n; i++)
{
    cout << "Input information for candidate number " << i + 1 << endl;
    cin.ignore(32323, 'n');
    cout << "Input ID(only 5 character):";
    gets(can[i].id);
    cout << "Input full name:";
    gets(can[i].fullname);
    do {
        cout << "Input reading mark:";
        cin >> can[i].reading;
        if(can[i].reading < 5 || can[i].reading>495)
            cout<<"Your reading mark is not between 5 and 495n";
    } while (can[i].reading < 5 || can[i].reading>495);
    do {
        cout << "Input listening mark:";
        cin >> can[i].listening;
        if(can[i].listening < 5 || can[i].listening>495)
            cout<<"Your listening mark is not between 5 and 495n";
    } while (can[i].listening < 5 || can[i].listening>495);

    can[i].total = can[i].reading + can[i].listening;
}
cout << endl << can[0].id<<endl;
}

所以我得到了这样的输出:

Input number of candidate:1

Input information for candidate number 1

Input ID(only 5 character):EW2RR

Input full name:Test1

Input reading mark:344

Input listening mark:233
EW2RRTest1 

fullname的值似乎是连续写入ID的。我已经尝试了很多方法来解决,但无法解决。有人知道吗?

在每个字符串中,如果你有一个字符串长度为N,你必须有一个字符数组的大小至少为N+1的'',这表明字符串在这里结束,cout停止打印。

在您的例子中,您声明了大小为5的字符数组,并使用字符填充所有5个字符,因此''放在其他地方。请注意,"id"answers"fullname"彼此相邻,所以我最好的猜测是,当你扫描"id"时,它应该是"id[5]"到"fullname[0]",然后当你扫描"fullname"时,它会替换这个"",所以"id"没有终止点,必须使用"fullname"的终止点。这就是为什么全名被附加到id后面。请注意,这不是默认行为,程序在其他机器上的行为可能不同。

另外,gets()是一个坏函数,如果您之前使用了cin或scanf,您应该先通过调用

来刷新stdin。
fflush(stdin);
在使用gets()之前

因为有时'n'留在stdin中但在您的情况下,这是由

处理的
cin.ignore(32323, 'n');

像Paul Rooney所说的那样使用fgets()更可取。我自己也有很多get的问题。

编码快乐! !

您需要在每个字符串的末尾放置一个终端''字符。

当ID被打印时,代码(cout)不会停止,直到它到达NULL