g ++编译和while循环

时间:2017-10-27 10:33:54

标签: c++ c++11

先决条件: Atom作为代码编辑器,使用gpp-compiler(插件),它使用g ++在编辑器中编译和运行cpp文件。
一些不是真正的示例代码来理解问题:

int main()
{
    int number;
    while(cin >> number)  
    {  
        cout << "Your number is " << number << endl;  
    }  
}  

所以这个程序可以通过g ++编译器轻松编译,问题出现在运行时,当编译程序在终端启动时......它只是不起作用。除了&#34;按任意键继续...&#34;甚至没有错误 那么编译器不能支持这个循环参数? (while(cin>>number)
是的,Atom中的gpp-compiler与其他类型的脚本一起工作正常 对不起,如果这个问题很愚蠢但我只是想知道为什么会这样。谢谢!

一些编辑:
是的。我无法胜任解释我的问题。所以我的问题不是while循环参数,我只是不理解为什么程序在空终端启动(上面有消息),而在我的手机上它也用g ++编译,程序运行完美.-。

1 个答案:

答案 0 :(得分:1)

(cin >> number)条件始终评估为true,直到您向其发送EOF字符。在Windows上,它是 Ctrl + Z 。您没有在标准输出上看到任何内容的原因是程序等待您输入值并按 Enter 。然后它进入无限循环。修改程序以包含一些简单的逻辑:

#include <iostream>

int main() {
    char choice = 'y';
    int number;
    while (std::cin && choice == 'y') {
        std::cout << "Enter the number: ";
        std::cin >> number;
        std::cout << "Your number is " << number << std::endl;
        std::cout << "Repeat? y / n: ";
        std::cin >> choice;
    }
}