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

标签 c++

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

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;
}

关于c++ - 如何从文件中的特定行读取 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59026156/

相关文章:

c++ - 使用此代码时,我不断收到错误消息。我正在尝试在继承类中使用构造函数。 C++

C++ 和 GCC : How Does GCC's C++ Implementation Handle Division by Zero?

c++ - 未正确推断对全局函数的引用

c++ - 在 C++ 中以相同的方式同时划分两个范围的元素

c++ - 获取 QStringList 的最后一个元素

c++ - 这如何解决访问冲突问题?

c++ - 避免内存泄漏

C++:使用指向大型静态数组的指针安全地初始化类

c++ - 为 C++ 项目报告的奇怪的 Klocwork 问题

c++ - boost::asio::ip::tcp::resolver::resolve() 永远阻塞