C++ 我试图在C+;中的数组末尾插入一个元素+;。为什么这种方法不起作用? intmain() { 常数int SIZE=100; int a[大小]; int输入,容量=0; cout(输入) { if(容量

C++ 我试图在C+;中的数组末尾插入一个元素+;。为什么这种方法不起作用? intmain() { 常数int SIZE=100; int a[大小]; int输入,容量=0; cout(输入) { if(容量,c++,arrays,insert,C++,Arrays,Insert,当以下循环中断时 while (cin >> input) { ... } 没有任何内容可从cin读取,或者cin处于错误状态。因此,尝试从cin读取在该行失败 cin >> element; 这就是为什么程序直接进入下一行 为了解决这个问题, 读取SIZE元素数后,中断while循环 通过输入错误的输入中断while循环。在这种情况下,您必须清除cin的状态,放弃一行输入,然后继续 您可以通过使用来完成这两个任务 while (capacity < S

当以下循环中断时

while (cin >> input)
{
   ...
}
没有任何内容可从
cin
读取,或者
cin
处于错误状态。因此,尝试从
cin
读取在该行失败

cin >> element;
这就是为什么程序直接进入下一行


为了解决这个问题,

  • 读取
    SIZE
    元素数后,中断
    while
    循环

  • 通过输入错误的输入中断
    while
    循环。在这种情况下,您必须清除
    cin
    的状态,放弃一行输入,然后继续

  • 您可以通过使用来完成这两个任务

    while (capacity < SIZE && cin >> input)
    {
        a[capacity] = input;
        capacity++;
    }
    
    // Did the while loop stop because of size or bad input?
    if ( capacity < SIZE )
    {
        // Bad input.
        // Clear the state of cin.
        // Read and discard the rest of the line.
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    

    为了在以下循环中断时能够使用
    std::numeric_limits

    while (cin >> input)
    {
       ...
    }
    
    没有任何内容可从
    cin
    读取,或者
    cin
    处于错误状态。因此,尝试从
    cin
    读取在该行失败

    cin >> element;
    
    这就是为什么程序直接进入下一行


    为了解决这个问题,

  • 读取
    SIZE
    元素数后,中断
    while
    循环

  • 通过输入错误的输入中断
    while
    循环。在这种情况下,您必须清除
    cin
    的状态,放弃一行输入,然后继续

  • 您可以通过使用来完成这两个任务

    while (capacity < SIZE && cin >> input)
    {
        a[capacity] = input;
        capacity++;
    }
    
    // Did the while loop stop because of size or bad input?
    if ( capacity < SIZE )
    {
        // Bad input.
        // Clear the state of cin.
        // Read and discard the rest of the line.
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    

    为了能够使用
    std::numeric\u limits

    对我来说,第一个循环填满了数组,第二个循环没有空间了。你试过调试吗?对我来说,第一个循环填满了数组,第二个循环没有空间了。你试过调试吗?