如何从文件中的特定行读取 (C++)

How to read from a specific line in a file (C++)

本文关键字:读取 C++ 文件      更新时间:2023-10-16

我需要找到输入一个数字并在我的文本文件中找到与数字对应的特定行,我遇到了一点麻烦,这是我到目前为止所拥有的:

cout << "Please enter the ID number of the student, to view their grades: ";
cin >> number;
ifstream myfile;
myfile.open("grades.txt");
if (myfile)
{
cout << "  ID      exam1    exam2    exam3" << endl;
cout << "---------------------------------" << endl;
getline(myfile, number);
myfile >> number >> exam1 >> exam2 >> exam3;

cout << setw(5) << number << setw(9) << exam1
<< setw(9) << exam2 << setw(9) << exam3 << endl;
cout << "---------------------------------" << endl;
total = exam1 + exam2 + exam3;
cout << "TOTAL: " << setw(25) << total << endl << endl;
}
myfile.close();
return 0;

}

是的,您可以使用 for 循环循环,直到到达行号,同时递增。

#include <iostream>
#include <fstream>
#include <string>
int main()
{
// Line #
int line;
// File
std::ifstream f("_"); 
// Text
std::string s; 
// Prompt
std::cout << "Line #: " << std::endl; 
// Store line #
std::cin >> line; 
// Loop, while less than line
for (int i = 1; i <= line; i++)
std::getline(f, s);
// Output text at line
std::cout << s;
return 0;
}

这将有所帮助:(

#include<iostream>
#include<vector>
#include<fstream>
#include<string.h>
#include<iomanip>
using namespace std;
int main()
{
int number;
cout << "Please enter the ID number of the student, to view their grades: ";
cin >> number;
ifstream myfile;
myfile.open("grades.txt");
if (myfile)
{
string string_obj;
string delimiter = " ";
int id,exam1,exam2,exam3;
size_t pos = 0;
cout << "  ID      exam1    exam2    exam3" << endl;
cout << "---------------------------------" << endl;
getline(myfile, string_obj);
//Split string into tokens
string token[4];
int i=0;
while ((pos = string_obj.find(delimiter)) != string::npos)
{
token[i++] = string_obj.substr(0, string_obj.find(delimiter));
string_obj.erase(0, pos + delimiter.length()); // move string for next iteration   
}
token[i] = string_obj.substr(0, string_obj.find(delimiter));
id = stoi(token[0]);
if (id == number)
{   
exam1 = stoi(token[1]); // convert string into int
exam2 = stoi(token[2]);
exam3 = stoi(token[3]);
}

cout << setw(5) << number << setw(9) << exam1
<< setw(9) << exam2 << setw(9) << exam3 << endl;
cout << "---------------------------------" << endl;
int total = exam1 + exam2 + exam3;
cout << "TOTAL: " << setw(25) << total << endl << endl;
}
myfile.close();
return 0;
}