Ahoura Ghotbi
Ahoura Ghotbi

Reputation: 2896

Read File line by line using C++

I am trying to read a file line by line using the code below :

void main()
{
    cout << "b";
    getGrades("C:\Users\TOUCHMATE\Documents\VS projects\GradeSystem\input.txt");
}

void getGrades(string file){

    string buf;
    string line;
    ifstream in(file);

    if (in.fail())
    {
        cout << "Input file error !!!\n";
        return;
    }

    while(getline(in, line))
    {
        cout << "read : " << buf << "\n";
    }

}

For some reason it keeps returning "input file error!!!". I have tried to full path and relative path (by just using the name of the file as its located in the same folder as the project). what am I doing wrong?

Upvotes: 1

Views: 1786

Answers (4)

Felice Pollano
Felice Pollano

Reputation: 33272

You did not escape the string. Try to change with:

getGrades("C:\\Users\\TOUCHMATE\\Documents\\VS projects\\GradeSystem\\input.txt");

otherwise all the \something are misinterpreted.

Upvotes: 5

Loki Astari
Loki Astari

Reputation: 264719

As Felice said the '\' is an escape. Thus you need two.

Or you can use the '/' character.
As windows has accepted this as a directory separator for a decade or more now.

getGrades("C:/Users/TOUCHMATE/Documents/VS projects/GradeSystem/input.txt");

This has the advantage that it looks much neater.

Upvotes: 2

zchenah
zchenah

Reputation: 2118

first, if you wanna say '\' in a string, you should put '\\', that's the path issue.

then, the string buf is not in connect to your file..

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126957

The backslash in C strings is used for escape sequences (e.g. \n is newline, \r carriage return, \t is a tabulation, ...), thus your string is getting garbled because for each backslash+character sequence the compiler is replacing the corresponding escape sequence. To enter backslashes in a C string you have to escape them, using \\:

getGrades("C:\\Users\\TOUCHMATE\\Documents\\VS projects\\GradeSystem\\input.txt");

By the way, it's int main, not void main, and you should return an exit code (usually 0 if everything went fine).

Upvotes: 0

Related Questions