G++ 编译和 while 循环

g++ compiling and while loop

本文关键字:循环 while 编译 G++      更新时间:2023-10-16

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

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

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

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

(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;
    }
}