Skipping whitespaces when reading a numeric text file

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.

-316966104
32627
1030857824
32766
-316812024
32627
1030857864
32766

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;
}

inData.close();

return 0;

}

Last edited on
Nothing wrong with this code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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).

Last edited on
There's no need to skip whitespaces since the stream will do it for you.
A jonnin said check that the file is open before using it.
1
2
3
4
5
6
ifstream inData("filename.txt");
if(!inData) // or if(!inData.good())
{
  perror("File error: "); // include <cstdio>
  return 1;
}

Topic archived. No new replies allowed.