使用 std::cin 作为输入的 C++ 代码中途崩溃

c++ code using std::cin as input crashes halfway

我目前正在 codeabbey 上做这个练习。 https://www.codeabbey.com/index/task_view/greatest-common-divisor

这是我的代码。

main.cpp

#include <iostream>

int main()
{
    int cases;
    int gcd[cases], lcm[cases];
    std::cin >> cases;             //first input for number of data to be input
    for(int x=0; x<cases; x++) {   //loop number of times = to cases
        int a, b;                  //for storing the two numbers
        std::cin >> a >> b;
        int atemp = a, btemp = b;  //need to hold initial value of a and b for lcm
        while (a!=b) {             //basically to calculate gcd.
            if(a>b)
                a-=b;
            else if (b>a)
                b-=a;
        }
        gcd[x] = a;                //store gcd for this case.
        lcm[x] = atemp * btemp / gcd[x];  // store lcm
    }

    for(int x=0; x<cases; x++) {
        std::cout << "(" << gcd[x] << " " << lcm[x] << ") ";   //output gcd and lcm for every case.
    }
}

但是,当我尝试 运行 它并使用网站提供的样本值时,它总是崩溃。下面是我作为输入复制到控制台的值列表。

22
567 10
38 2
4214 2150
489 7459
82 5069
4200 784
4720 1770
2200 1440
6637 1
4984 7
1197 525
9905 472
648 552
7068 5700
22 2
2610 2160
7 7874
3663 3267
25 75
5985 3402
3337 5751
998 7895

当我复制整块值作为输入时,它不起作用。我尝试手动输入,发现它总是在输入的第 11 行结束(即 4984 7 的行)。我认为我的代码非常简单,应该不会出错...所以我想知道这里是否发生了我不知道的事情。

首先,请注意可变长度数组 (VLA) 不是 标准 C++ 的一个特性,尽管一些编译器(喜欢g++)支持他们。

考虑到这一点,请注意您正在声明您的 VLA - 每个大小 cases before 您已分配cases 的值!因此,数组的大小将是未定义的(可能为零)。

要解决此问题,您应该将数组的声明移动到 之后 读取 cases 值的行:

int cases;                    // Variable is declared here BUT HAS NO VALUE ASSIGNED
//int gcd[cases], lcm[cases]; // WRONG - what value is "cases?"
std::cin >> cases;            // First input for number of data to be input
int gcd[cases], lcm[cases];   // NOW we can declare the VLAs, knowing the "cases" value!
//...

但是,要使您的代码与 标准 C++ 兼容,您应该使用 std::vector 容器 class;所以,代替:

int gcd[cases], lcm[cases];

使用:

std::vector<int> gcd(cases), lcm(cases);

您可以继续使用 gcd[x] 语法访问两个向量的元素,因为 std::vector 提供了 [] 运算符。