简体   繁体   English

如何逐字读取txt文件的一行[C ++]

[英]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

}
  1. Read a line of text using std::getline . 使用std::getline读取一行文本。
  2. Read each token from the line by using a 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.

相关问题 如何从文件一次读入数组一个单词 - c++ How to read from a file into array one word at a time 在C ++中从.txt文件中查找垂直词 - Finding a vertical word from a .txt file in C++ 如何从非结构化的.txt文件中读取单词并将每个单词存储在C中的char数组中? - How to read words from unstructured .txt file and store each word in a char array in C? C ++-&gt;尝试逐字读取一行文本。 如何使指针等效于用于存储输入的当前二维数组 - C++ ->Trying to read a line of text word by word. How to make a pointer equivalent of the current 2 dimensional array used to store the input 从文件中读取行并将每个单词存储到数组(C语言)中 - read line from file and store each word into an array (C language) 在 c 中读取文件的第二个字 - Read second word of a file in c 如何将.txt文件逐行读取到C数组中? - How to read a .txt file into C array line by line? 如何从 C 上的 a.txt 文件的第二行开始读取内容 - How to read the content from the second line onwards on a .txt file on C C ++:如何读取大型txt文件并更快地保存到数组中 - C++: How to read large txt file and save to array faster 如何将单词从.txt文件复制到数组中。 然后将每个单词打印在单独的行上 - How to copy words from .txt file into an array. Then print each word on a separate line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM