I am trying to read (and output) a numeric text file filled with thousands of numbers (around 8000), but it is not working it keeps outputting random numbers, e.g.
also, how do I skip white spaces, the numeric file I am trying to read has around 7 white spaces before each number. I went in and deleted the white spaces for around 10 numbers, and tried my code and i still get a random output. So first I need to have it output the right numbers, and then I need to figure out how to edit the code to skip the white spaces before reading each number.
#include<iostream>
#include<fstream>
using namespace std;
int main ()
{
int data[8192];
ifstream inData;
inData.open("filename.txt");
for (int i=0;i<8191;i++)
{
inData >> data[i];
cout << data[i] << endl;
}
#include<iostream>
#include<sstream>
#include <vector>
#include <string>
int main ()
{
std::vector<int> data;
std::stringstream inData;
inData << "1 22 44 55 77 4413 -123123 3123";
//inData.open("filename.txt");
while (!inData.eof())
{
int i;
inData >> i;
data.push_back(i);
std::cout << i << std::endl;
}
std::cout << "done." << std::endl;
return 0;
}
Check what your file looks like in hex, maybe those white spaces are not what you think. Note windows makes newlines = /r /n, but C++ sanitizes it for you unless you use the binary flag.
any chance your numbers are too large for the integer size?
also, be SURE it actually opened the file.
some compilers will ignore this fact and then feed you junk if you try to use the file that didnt open.
if nothing else code the full path and filename not just the filename, that should do it, but you probably want to get in the habit of checking if the file opened or not before using it via inData.good() or something (Ill be honest, its late and I am forgetting which flag is the best to check if it opened).