代码之家  ›  专栏  ›  技术社区  ›  Scaramouche

跳过到下一个迭代

  •  0
  • Scaramouche  · 技术社区  · 7 年前

    我试图从for循环中的用户输入、整数值中读取值。当用户按Enter时,我需要循环跳过当前迭代。像这样。

    short value;
    for(short i = 0; i < size; i++){
        cout << "Enter value. If you don't feel like it, press enter.";
        cin >> value;
        if(value is different from ENTER)
            cout << "did something with " << i << endl;
        else{ //off to next iteration
            cout << "did nothing with " << i << endl;
        }
    }
    

    样本运行:

    //input for size = 3
    15Enter
    Enter
    34Enter
    
    //output
    did something with 0
    did nothing with 1
    did something with 2
    

    我在很多地方见过 cin 不是最好的候选,但我没有找到一个可以应用于读取整数而不是字符串的示例。

    注意:我不想确认输入的是一个整数,我只需要知道它是否只是一个回车,然后忽略它,继续下一个迭代。

    桑克斯

    1 回复  |  直到 7 年前
        1
  •  0
  •   mansio    7 年前

    可能使用:继续

    使用Continue时,当前循环为Skip。

    如果你能做到:如果(值!='\n')…

    \ n为回车

    编辑:

    for(short i = 0; i < 10; i++){
                cout << "Enter value. If you don't feel like it, press enter.";
                if(cin.get()!='\n'){
                    cout << "did something with " << i << endl;
                    cin.clear();
                    cin.ignore();
                }
                else{ //off to next iteration
                    continue;
                }
            }
    }