1

I am trying to open a file and read the contents into a couple arrays. I can't find what I am doing wrong. I am using the absolute path. The input file looks something like this:

Sam     100    23   210
Bob     1     2    12
Ted     300   300   100
Bill    223   300   221
James   234   123   212
Luke    123   222   111
Seth    1     2     3
Tim     222   300   180
Dan     222   111   211
Ben     100   100     2

Here is my code:

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

using namespace std;

int main()
{
string name;
ifstream inFile;
string bowlerNames[10];
int bowlerScores[10][3] = {0};


inFile.open("C:\\Users\Seth\Documents\bowlingData.txt");

if (inFile.is_open()) //Checking if the file can be opened
{

for (int i = 0; i < 10; i++)
{
    inFile  >> bowlerNames[i] 
            >> bowlerScores[i][0]
            >> bowlerScores[i][1]
            >> bowlerScores[i][2];
}

for (int i = 0; i < 10; i++)
{
    cout    << bowlerNames[i] 
            << bowlerScores[i][0]
            << bowlerScores[i][1]
            << bowlerScores[i][2];
}
}
else cout << "Unable to open file..." <<endl; //Gives that sentence if the file can't be opened

inFile.close();

cout << endl; //spacing
system("Pause");
return 0;
}
Fabio Cardoso
  • 1,181
  • 1
  • 14
  • 37
setherj
  • 91
  • 1
  • 11

1 Answers1

2

All the backslashes have to be double backslash!

inFile.open("C:\\Users\\Seth\\Documents\\bowlingData.txt");

Confirm this for yourself by doing something like this:

string fileName = "C:\\Users\\Seth\\Documents\\bowlingData.txt");
cout << fileName << endl;
Floris
  • 45,857
  • 6
  • 70
  • 122
  • That seems like it will work. But why wouldn't it open when I just had the file name in there (with no backslashes). I had both the files in the same directory to my knowledge. – setherj Apr 12 '13 at 23:00
  • I can't answer the question "why didn't it open when I used a relative path" - not enough information, sorry. Glad that it worked like this, though. – Floris Apr 12 '13 at 23:06
  • I had inFile.open("bowlingData.txt"); but yet it was not opening, even when they were in the same directory. – setherj Apr 12 '13 at 23:08
  • To start, I would look at [this answer](http://stackoverflow.com/questions/875249/how-to-get-current-directory) and use the method given there to confirm you are indeed starting from the directory you think you're starting from... There is more helpful information in the answers to [this question](http://stackoverflow.com/questions/3772215/how-do-i-open-a-c-file-with-a-relative-path). Hope that helps. – Floris Apr 12 '13 at 23:15