【问题标题】:trying to give a variable to ifstream in c++ [duplicate]试图在c ++中为ifstream提供一个变量[重复]
【发布时间】:2019-12-30 08:37:07
【问题描述】:

我是 C++ 新手,并试图在这一行添加一个变量:ifstream studentPaper(paper); 生病将纸张传递给此功能并想在那里使用它。字符串纸有我的文件位置(/name/file.txt)

如果我把我的文件名放在那里,我不会收到任何错误 = ifstream studentPaper("/name/file.txt"); 但是当我将文件位置保存到一个字符串中并给它一个字符串时,我会得到错误 = ifstream studentPaper(paper);

我怎样才能做到这一点而不会出错

void matchGrades(string paper) {
string aa= "asd";
ifstream studentPaper(paper);
ifstream base("base.txt");
int grade=3;
while ((!studentPaper.eof()) && (!base.eof())) {
    string l1,l2;
    getline(studentPaper,l1);
    getline(base,l2);
    if(l1==l2){
       grade += 3;
    } else {
        grade -= 3;
    }
}
studentPaper.close();
base.close();
cout << grade;

【问题讨论】:

    标签: c++ file


    【解决方案1】:

    我认为你必须使用删除的字符串参数"/name/file.txt"
    因为参数分割空间。

    【讨论】:

      【解决方案2】:

      试试ifstream studentPaper(paper.c_str())

      此外,如果您的文件位于 main.cpp 所在的位置,则无需指定路径。像这样的:

      string studentFile = "student_file.txt";
      

      根据提供的信息。如果您仍然收到错误,请发布,以便我调整答案。

      【讨论】:

      • 没问题。我很高兴能提供帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      相关资源
      最近更新 更多