I'm attempting to open a file and read a series of ints from it in C++. I was under the impression that this could be done by simply using inputfile >> variable. However, even the first item is reading in incorrectly. I wrote the simplest possible code to replicate my problem.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv) {
int n;
ifstream inputfile("input.txt");
inputfile >> n;
cout << "NUMBER IS: " << n << endl;
return 0;
}
The input file is simply a text file containing the number 4. However, I get a different large number out every time I test the code. What's the issue?
Add checks like this:
if(inputfile>> n)
{
//Code
} else
{
cout << "Failed!";
}
Also, check the file was opened:
ifstream inputfile("input.txt");
if (!inputfile)
{
cout << "Failed opening file!";
return -1;
}
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.