存储字符数组值错误(c++)
Store char array value error(c++)
我试图使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
。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'