[英]Read input from istream until EOF
I am having trouble understanding how to read from istream for my code. 我无法理解如何从istream读取我的代码。 The program assignment I am trying to do is retrieve input from user or from an input file from the cmdline (ie. ./ < input.txt).
我要执行的程序分配是从用户或cmdline的输入文件(即./ <input.txt)中检索输入。 The user input values are passed to a function that determines if it is a prime number or not.
用户输入值将传递到确定它是否为质数的函数。 The issue is when I pass an input file (ie. input.txt) with multiple integers or characters, it only reads the first one and the program ends.
问题是当我传递带有多个整数或字符的输入文件(即input.txt)时,它仅读取第一个,程序结束。 I have read many questions and answers, but many of the solutions I have tried do not work.
我已经阅读了许多问题和答案,但是我尝试过的许多解决方案都行不通。
For example, input.txt holds: 例如,input.txt包含:
2 3 4 5
or 要么
2
3
4
5
Here is my program, I won't provide my isPrime function as I believe it working just fine. 这是我的程序,我不会提供isPrime函数,因为我认为它可以正常工作。 It is just the issue with passing the input file to be read until end-of-file.
传递要读取的输入文件直到文件结束只是问题。 Should I be using ifstream isntead?
我应该使用ifstream istead吗? I was given a hint to use a while loop to read till end-of-file but that just keeps spitting the same first data I input in the program.
我得到了一个提示,可以使用while循环读取直到文件结束,但这只会使我在程序中输入的第一个数据不断吐出。
#include <iostream>
#include <cstdlib>
#include <limits>
using namespace std;
bool isPrime(int) { // Example return for isPrime
return false;
}
int main(int argc, char *argv[]){
// Initialize input integer
int num = 0;
cout << "Enter number to check if prime: ";
cin >> num;
// while loop to detect bad input
while(!(cin >> num)){
cin.clear(); // clear error flag
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //ignores bad input
} // end while
while(cin >> num){ // while there is valid input, do isPrime
if(isPrime(num)){
cout << "prime\n";
} else {
cout << "composite\n";
}
} // end while
return 0;
} // end main
You are using the while
loop incorrectly. 您正在错误地使用
while
循环。
Use: 采用:
int main(int argc, char **argv)
{
int num = 0;
// Keep reading from stdin until EOF is reached or
// there is bad data in the input stream.
while ( cin >> num )
{
if(isPrime(num)){
cout << "prime\n";
} else {
cout << "composite\n";
}
}
return 0;
} // end main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.