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;
}
2
  • What is the output from your program ? Commented Apr 12, 2013 at 23:01
  • The output before I fixed the backslash problem (Thx Floris) was "unable to open file" :) Commented Apr 12, 2013 at 23:02

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
I had inFile.open("bowlingData.txt"); but yet it was not opening, even when they were in the same directory.
To start, I would look at this answer 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. Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.