i have to write a code that prompts user to enter a file name (containing 2 columns of integer). The program then reads that file, prints out the numbers set.
My txt file looks like this (the numbers are separated by space):
2 3
5 6
7 8
8 9
5 7
I thought it would be easy, but now i stuck. When i run the program, this line appeared
"There're no number in the file."
I set number to "int", so why can't the compiler read the number? But when i change the type to "string", the numbers did appear O_O , since i later need to calculate the average of those num also, i cannot use string.
Here is my code, I appreciate any help TT___TT
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream in_file;
string filename;
int number;
int number1;
cout << "In order to process, please enter the file name: ";
cin >> filename;
in_file.open(filename.c_str());
if (!in_file.is_open())
{
cout << "Cannot open file" << endl;
}
else
{
in_file >> number;
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
}
system("pause");
return 0;
}
Error in your logic:
in_file >> number; // Assigns 2 from first line to number
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1) // Assigns 3 to number from first line
// and assigns 5 to number1 from second line
{
cout << number << " " << number1;
}
You need to use just:
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
If you must print "There're no number in the file." in the output, you can use:
bool gotSomeNumbers = false;
while (in_file >> number >> number1)
{
cout << number << " " << number1;
gotSomeNumbers = true;
}
if (!gotSomeNumbers)
{
cout << "There're no number in the file." << endl;
}
The method you are using to find to know whether file is empty is not correct in following way :: As soon as this line gets executed
in_file >> number;
The compiler will treat first line as an integer as a whole , ie number = "2 3" in given scenario. now this is not a standard number because of space in between 2 and 3 and
in_file.fail()
will return true.The Correct way is to use "eof" function as follows : (I also added 1-2 lines to calculate average of these numbers as you mentioned)
Reference : When will ofstream::open fail? Checking for an empty file in C++
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.