c++ - 当char数组被过度填充时,为什么我的程序会陷入无限循环?

标签 c++ arrays loops while-loop

我正在尝试用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/

相关文章:

C++ 不正确的循环算法(或文件处理问题)

javascript - 通过循环遍历另一个数组来填充一个新数组

在循环内定义的 Java 变量似乎在循环外无法识别?

c++ - 如何将 Windows 窗体应用程序 (C++) 设置为具有 Aero/Glass 背景?

c++ - 调用虚函数和非虚函数的区别?

c++ - 在 C++ 中作为参数传递时变量何时被复制?

c++ - 可能的死锁情况 : interrupt and mutex

javascript - if 语句用于根据电子邮件检查用户是否获得授权

c++ - 如何对齐堆中的数组?

javascript - 不要在循环 Javascript 中创建函数