【问题标题】:Read particular line from text file using C++使用 C++ 从文本文件中读取特定行
【发布时间】:2015-10-05 11:25:50
【问题描述】:
#include <iostream.h>

#include <stdlib.h>
#include <fstream.h>
#include <iomanip.h>
#include <string.h>
#include <conio.h>
int view(void)
{ 
  ifstream in("NewFaculty.txt");

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  char str[255];

  while(in) {
    in.getline(str, 255);  // delim defaults to '\n'
    if(in) cout << str << endl;
  }

  in.close();
  getch();
  return 0;
}

int main()
{
  view();
}

我有这段代码用于从 C++ 中的文本文件中检索数据。使用此代码,我将整个文件数据作为输出,例如:

          name     address    id
          xxx      hyd       0001
          yyy      hyd       0002

但我需要通过接受键盘输入来输出特定的数据行。需要像这样的输出:

          name     address    id
          xxx      hyd        0001

我的输入是name。请任何人以这种方式提供帮助。

【问题讨论】:

  • 是的,我需要修复它,但我不知道。
  • 键盘输入的是什么(id、姓名、地址、行号)?
  • 使用 std::istream::ignore,查看现有答案中的详细信息:stackoverflow.com/a/25012566/492336
  • 阅读时需要检查每一行。首先提取名称列,然后将其与您输入的名称进行比较以查看它们是否匹配。如果他们这样做,请打印该行并停止。否则不要打印该行并继续。

标签: c++ turbo-c++


【解决方案1】:

我会将每一行的值存储在这样的结构中:

struct RecordLine
{
   std::size_t lineNo; // optional
   std::string name;
   std::string address;
   std::string id;
};

然后我会检查键盘输入,如果是,则打印该行。小心先读取键盘输入,然后在文件中搜索。但是你可以使用一个类,带有读取行的方法(这样会更好)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多