我正在尝试用C++编写一个程序,该程序允许用户将正整数和名称输入固定大小的数组中并打印出来。从首次启动该程序开始输入正确的数据后,该程序似乎可以正常运行。
我遇到的问题是当为Char数组输入不正确的值时(超出字符数)。如果我为char数组输入了不正确的值,它会按预期发出警告消息,但是一旦我输入了正确的大小字,程序就会进入无休止的循环,要求输入已输入的值。
我的代码如下:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int count = 1;
int num = 0; // variable for positive integer
char name[31]; //char array to store name inside
while(count != 0){
cout << "Please enter the number: " << endl;
cin >> num;
while(num < 1){
cout << "Number must be a positive integer!" << endl; //Loop that checks whether the
cin >> num; // entered number is a positive
} // integer.
cout << "Please enter the name: " << endl;
cin >> name;
while(strlen(name) > 30){ //Loop that checks whether the
cout << "Name exceeds the allowed character count!" << endl; //entered name exceeds the
cin >> name; // allowed character count.
}
--count;
};
cout << num << " " << name;
return 0;
}
我试图理解为什么如果我先输入错误的值然后输入正确的值,我的程序为什么会陷入无限循环?与超出数组的字符数有关吗?
任何帮助将不胜感激,非常感谢!
最佳答案
这个循环是有问题的:
while(strlen(name) > 30) { //Loop that checks whether the
cout << "Name exceeds the allowed character count!" << endl; //entered name exceeds the
cin >> name; // allowed character count.
}
如果有31个字符,然后是
strlen()
,则'\0'
将返回31。因此,这已经超出了31个元素的长数组所能容纳的范围。但这不是最小的问题-从cin
加载比数组大小更多的字符后,您就会遇到 undefined 的行为领域-从C++ 17开始,如果满足以下条件,则cin
会很高兴地写出c样式数组的容量你告诉它这样做。我建议您使用
std::string
而不是原始C数组。他们为您处理以null终止的字符串技术。
关于c++ - 当char数组被过度填充时,为什么我的程序会陷入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61962124/