如何使用Ctrl + D在C ++中激活EOF?

时间:2018-02-03 05:07:42

标签: c++

我之前从未使用过EOF,我想知道如何创建一个继续运行的代码,直到我按Ctrl + D激活EOF。这是我的一般想法:

int main(){
    int num;
    while (!EOF) { //while the EOF is not activate
        cin >> num; //use cin to get an int from the user
        //repeatedly give feedback depending on what int the user puts in
        //activate EOF and end the while loop when the user presses "Ctrl + D"
    }
}

那么当用户按下Ctrl + D时,如何将其设置为结束?谢谢!

2 个答案:

答案 0 :(得分:3)

这是一个使用整数和EOF检查的工作示例。

#include <iostream>

int main(int argc, char *argv[]) {

  int num;

  for (;;) {

    std::cin >> num;
    if (std::cin.eof()) break;
    std::cout << "Number is " << num << std::endl;

  }

  return 0;

}

答案 1 :(得分:2)

尝试

int main(){
    int num;
    while (cin >> num) { 
       // ...
    }
}
相关问题