【问题标题】:Why are these files not opening? [duplicate]为什么这些文件打不开? [复制]
【发布时间】:2015-11-16 01:23:20
【问题描述】:

从第一天开始,我就遇到了用 C++ 打开文件的问题,现在又遇到了重新打开特定文件的问题。难道我做错了什么?我已经尝试过这个部分,无论后面有没有“.txt”,以及将它放入 C 驱动器并试图以这种方式获取它,但它仍然无法正常工作。

代码:

ifstream correctAnswers;
ifstream studentAnswers;

correctAnswers.open("C:\CorrectAnswers");
studentAnswers.open("C:\StudentAnswers");

if (correctAnswers && studentAnswers) {
    for (int i = 0; i < SIZE; i++) {
        correctAnswers >> answerKey[i];
        studentAnswers >> studentKey[i];

    }
}
else {
    cout << "error" << endl;
}

错误部分一直显示,所以我假设这意味着文件尚未打开或文件的内容将被复制到数组中。

【问题讨论】:

    标签: c++ io fstream


    【解决方案1】:

    文件名字符串中需要双反斜杠。

    correctAnswers.open("C:\\CorrectAnswers");
    studentAnswers.open("C:\\StudentAnswers");
    

    【讨论】:

      【解决方案2】:

      C (C++) 字符串中的'\' 引入了转义序列。要获得实际的 '\',您需要逃脱转义 - 即 "C:\\CorrectAnswers"

      一个好的编译器(具有正确的错误/警告配置)通常会说“未知转义序列 \C”。

      【讨论】:

        【解决方案3】:

        哦,我的主。谢谢你们。我这里有一个完整的程序,由于那个特定的部分而无法工作。我还必须在末尾添加“.txt”以将其指向正确的方向。 ;)

        ifstream correctAnswers;
        ifstream studentAnswers;
        
        correctAnswers.open("C:\\CorrectAnswers.txt");
        studentAnswers.open("C:\\StudentAnswers.txt");
        
        if (correctAnswers && studentAnswers) {
            for (int i = 0; i < SIZE; i++) {
                correctAnswers >> answerKey[i];
                studentAnswers >> studentKey[i];
        
            }
        }
        else {
            cout << "error" << endl;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-20
          • 2016-03-05
          相关资源
          最近更新 更多