使用C++逐行读取文件

Aho*_*tbi 1 c++

我正在尝试使用以下代码逐行读取文件:

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

}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它不断返回"输入文件错误!!!".我已尝试完整路径和相对路径(通过使用文件的名称,因为它位于与项目相同的文件夹中).我究竟做错了什么?

Fel*_*ano 5

你没有逃脱字符串.尝试改变:

getGrades("C:\\Users\\TOUCHMATE\\Documents\\VS projects\\GradeSystem\\input.txt");
Run Code Online (Sandbox Code Playgroud)

否则所有\的东西都被误解了.

  • 或者你可以使用正斜杠.他们仍然会在Windows上工作. (4认同)