【问题标题】:How to break out of this for loop: `for (; cin >> A;);`如何打破这个 for 循环:`for (; cin >> A;);`
【发布时间】:2015-05-08 18:34:25
【问题描述】:
for (cout << "\nEnter the Sentence now:";
    cin >> Ascii;

cout << "The ascii value of each letter you entered, added to the offset factor is: " 
     << (int)Ascii + RandomNumberSubtract << endl);

【问题讨论】:

  • WT...你为什么要这样做?
  • 我认为您需要发布更多代码,以便想要帮助您的人了解您在做什么。
  • 一个 for 循环执行下一条语句,而这总是只有一件事。但是您的“for循环”格式不正确。你应该查一下,但我将提供的提示是“for (int i=0; i

标签: c++ loops for-loop break


【解决方案1】:

也许最好的建议是不要聪明。您不仅让其他人*难以阅读、理解和修改您的代码,而且还冒着智取自己的风险。

因此,不要试图做奇怪而聪明的事情来实现你的循环。只是自然地做事。如果它们自然不适合forwhiledo ... while 语句的结构,那么只需编写一个通用循环并使用break 语句来处理退出循环。例如

while (true) {
    // Some stuff
    if (i_should_break_out_of_the_loop) {
        break;
    }
    // Some more stuff
}

这总是比以你的方式折磨 for 声明要好得多。

一旦您有了一个清晰、易于理解的循环,就应该相对容易地对其进行修改以满足您的需要。 (或提出更清晰、更集中的问题)

*:“任何其他人”也包括从现在起三周后的你,在你有时间离开你的短期记忆之后。

【讨论】:

    【解决方案2】:

    我强烈建议您将此循环转换为while 循环。但是,无论您是否这样做,以下都是正确的:

    只要输入一个EOF,循环就会终止。

    EOF 的输入方式取决于您的操作系统(也可能取决于您的终端设置)。在 Linux 上(在默认终端设置下),您会在行首按 Ctrl+D 获得 EOF。在 Windows 上,我认为是 Ctrl+Z。在 Mac 上我不知道。

    当然,您也可以将程序的标准输入重定向为来自文件(在这种情况下,EOF ——正如你猜想的那样——在文件末尾生成),或者来自管道(在这种情况下,EOF 生成为编写程序关闭管道后立即)。

    如果变量 Ascii 不是 char 或 string 类型,您还可以输入无法解析为该变量数据类型的内容(例如,如果读取 int,除数字之外的任何内容都会导致流报告失败,因此循环终止)。

    您可能还想添加另一个结束条件,然后 在循环主体中(在您的 for 循环中当前只是一个空语句)。例如,您可能决定用百分号终止循环;那么你可以写(我仍然假设你没有提供的Ascii的类型是char):

    cout << "\nEnter the Sentence now:";
    while(cin >> Ascii)
    {
       cout << "The ascii value of each letter you entered, added to the offset factor is: " 
            << (int)Ascii + RandomNumberSubtract << endl);
       if (Ascii == '%')
         break;
    }
    

    但是请注意,通常operator&lt;&lt; 会跳过空格;我猜你不想跳过空格。因此,您可能不应该使用operator&lt;&lt;,而是使用get;这也将允许您使用行尾作为结束条件:

    cout << "\nEnter the Sentence now:";
    while(std::cin.get(Ascii) && Ascii != '\n')
    {
       cout << "The ascii value of each letter you entered, added to the offset factor is: " 
            << (int)Ascii + RandomNumberSubtract << endl);
    }
    

    但是在这种情况下,最好一步读取该行,然后遍历它:

    cout << "\nEnter the Sentence now:";
    std::string line;
    std::getline(std::cin, line);
    for (std::string::iterator it = line.begin; it != line.end(); ++it)
    {
      cout << "The ascii value of each letter you entered, added to the offset factor is: " 
            << (int)*it + RandomNumberSubtract << endl;
    }
    

    请注意,在 C++11 中,您可以将其简化为

    cout << "\nEnter the Sentence now:";
    std::string line;
    std::getline(std::cin, line);
    for (auto ch: line)
    {
      cout << "The ascii value of each letter you entered, added to the offset factor is: " 
            << (int)ch + RandomNumberSubtract << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多