[英]How to read a single line of txt file word by word [C++]
I need to read a single line of a given file word by word. 我需要逐字读取给定文件的一行。 The file is a register of exam grades by different students.
该文件记录了不同学生的考试成绩。 In particular, for any student there is a first line formatted as follows:
特别是,对于任何学生,第一行的格式如下:
-name- -surname- -名字姓-
Then, there is a second line reporting the grades of every exam using the following format: 然后,第二行使用以下格式报告每次考试的成绩:
-grade 1- -grade 2- -grade 3- [...] -grade n- 等级1-等级2-等级3- [...]-等级n-
I created a class Student and want to put the grades in an array of int. 我创建了一个学生类,并希望将成绩放入一个int数组中。 I know how to read the file word by word, but I have no idea how to stop once the grades from a student are over (since I don't know how may grades any given student has beforehand).
我知道如何逐字阅读文件,但我不知道一旦学生的成绩结束就如何停止(因为我不知道任何给定学生的成绩如何。) I thought to write a while repetition statement, but I have no idea what the condition could be.
我本想写一段重复的语句,但我不知道情况会怎样。
Is there a way to read a line word by word and then stop reading once the line is over? 有没有一种方法可以逐字读取一行,然后在行结束后停止读取?
This is what I managed to write until now: 这是我到目前为止写的:
cout << "Inserisci il nome del file da analizzare: " << endl;
cin >> _filename;
fstream myfile;
myfile.open(_filename);
if (myfile.is_open())
{
myfile >> _name >> _surname >> ; //reading name and surname
}
std::getline
. std::getline
读取一行文本。 std::istringstream
. std::istringstream
从行中读取每个令牌。 std::string line;
if ( ! std::getline(myfile, line) )
{
// Problem reading the line.
// Deal with error.
}
else
{
// Read line successfully.
std::istringstream str(line);
std::string token;
while ( str >> token )
{
// Use token.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.