如何在c ++中声明文件? [英] How to declare a file in c++ ?
问题描述
我已经创建了一个名为(student.txt)的文件,我将以下信息放在文件中
Will Smith 99
Sarah Johnson 100
Tim Howard 70
Francesco Totti 95
Michael Jackson 92
我想要求用户输入文件名,一旦输入文件名,我想通过读取数据来显示平均分数文件。
注意:文件中的每一行都包含学生的名字,姓氏和考试成绩。
这是我到目前为止所做的,这只能显示文件里面的内容
请帮我声明文件名并显示平均分数学生
I have already created a file called ( student.txt) and i put the following information inside the file
Will Smith 99
Sarah Johnson 100
Tim Howard 70
Francesco Totti 95
Michael Jackson 92
I want to ask the user to enter the file name,once they enter the file name, I want to displays the average score by reading the data from the file.
Note : Each line in the file contains the first name, last name, and test score of a student.
Here's what i did so far and this could only display what inside the file
Please help me to declare the file name and to display the average score of a student
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string studentFile;
ifstream file("student.txt");
if (file.is_open()) {
while (getline(file,studentFile))
{
cout << line << '\n';
}
file.close();
}
推荐答案
您应该使用ifstream进行输入。
阅读: http://www.cplusplus.com/doc/tutorial/files/ [ ^ ]
和: http://www.cplusplus.com/reference/fstream/ifstream/open/ [ ^ ]
然后:
You should be using ifstream for input.
Read this: http://www.cplusplus.com/doc/tutorial/files/[^]
and:http://www.cplusplus.com/reference/fstream/ifstream/open/[^]
Then:
ifstream studentfile;
string studentfilename;
cout << "Please enter the student file name = ";
cin >> studentfilename;
studentfile.open(studentfilename);
open()中的std :: string参数仅在C11中合法。
std::string argument in open() is legal in C11 only.
这篇关于如何在c ++中声明文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!