【发布时间】:2020-11-29 00:53:22
【问题描述】:
这是我的代码,想知道为什么它不会从文件中读取。或者更好的问题是如何从文件中提取学生姓名。我做错了什么?
int semestersCompleted;
int gpa;
double semesterDiscount;
double semesterDiscount;
double gpaDiscount;
double totalDiscount;
string studentName;
int main(void)
{
outFile << "Task 1 - tuition Discount" << endl;
ifstream dataFile;
ofstream outFile;
getline(dataFile, studentName, '\n');
dataFile >> semestersCompleted;
dataFile >> gpa;
dataFile.ignore(100, '\n');
outFile << "Name: " << studentName << endl;
outFile << "Semester Completed: " << semestersCompleted << endl;
outFile << "GPA: " << gpa << endl;
}
【问题讨论】:
-
我们可以看看
dataFile和outFile的输入文件和声明/初始化吗? -
感谢您发布整个程序。您似乎在声明一个 ifstream 和一个 ofstream,但实际上并没有让它们读取或写入任何文件。尝试添加
dataFile.open("input_file");,然后添加outFile.open("output_file");。 -
你有没有用
dataFile.open("foobar.txt")打开你的输入文件? -
所以对于每个人来说,我确实打开了文件,它在输出文件中打印了“任务 1 - 学费折扣”,只是没有读取输入文件来写出 studentName(我很抱歉还是个新手)
-
检查文件是否用
dataFile.is_open()打开。如果它返回 false,那么您就知道程序无法正确打开文件。如果输入文件在调试文件夹中,大多数 IDE 直接读取输入文件,否则使用文件路径。编辑:您的代码没有显示您的 dataFile 没有打开任何文件。
标签: c++ visual-studio visual-c++