Search code examples
c++visual-c++file-iofstreamifstream

Having reading numbers from a *.txt file in C++ using fstream


I have a *.txt files having integers, one on each line. So the file would look something like

103123
324
4235345
23423
235346
2343455
234
2
2432

I am trying to read these values from a file line by line so I can put them in an array. Below is some code I wrote to achieve that

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int nArray[1000];
int i = 0;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream file("C:\Users\Chinmay\Documents\Array.txt");
    //fstream file("C:\Users\Chinmay\Documents\Array.txt", ios_base::out );
    //fstream file();
    //file.open("C:\Users\Chinmay\Documents\Array.txt", ios_base::out );

        bool b = file.is_open();
    //file.seekg (0, ios::beg);
    int i = file.tellg();
    while(!file.eof())
    {
        //string str;
        //getline(file, str);
                //nArray[i++] = atoi(str.c_str());
        char str[7] = {};
        file.getline(str,7);
        nArray[i++] = atoi(str);
    }
    file.close();
    return 0;
}

The file opens as the bool 'b' returns true. But the while loop exits in one run. and the array is empty. I looked up online and tried other things like the code given here at

code tutorial

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int nArray[100000];
int i = 0;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream in("C:\Users\Chinmay\Documents\Array.txt");
    bool b = in.is_open();

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  char str[255];

  while(in) {
    in.getline(str, 255);  // delim defaults to '\n'
    if(in) cout << str << endl;
  }

  in.close();

  return 0;

}

This returns immediately as well. The file opens but no data is read. The file is not empty and has the data in it. Could someone explain where I am going wrong? I am using Visual Studio 2011 beta.


Solution

  • This isn't doing what you think it's doing:

    ifstream file("C:\Users\Chinmay\Documents\Array.txt");
    

    Use forward slashes (even on Windows) and check the file open succeeded immediately:

    std::ifstream ifs("C:/Users/Chinmay/Documents/Array.txt");
    if (!ifs) 
    {
        // Failed to open file. Handle this here.
    }