【问题标题】:reading records from text file从文本文件中读取记录
【发布时间】:2012-10-09 22:58:26
【问题描述】:

好的,我是 C++ 新手,但我正在做很多练习。

这是我的问题,有人可以看看我的源代码,并在这里引导我朝着正确的方向前进。

这就是我想要做的。

  1. 程序应该能够读取带有记录的文本文件 在里面。(做到了)
  2. 我还想在文本文件中使用字符串搜索记录 (没做过)
  3. 另外,使用小数从高到低对记录进行排序 文本文件中的数字或双精度。我想使用冒泡排序 功能。

这是我的代码

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//double gpa;
//string

int main () 
 {
  string line;
  ifstream myfile ("testfile.txt");
  if (myfile.is_open())
 {
    while ( myfile.good() )
 {
      getline (myfile,line);
      cout << line << endl;

 }
    myfile.close();
 }

else cout << "Unable to open file"; 

char c;
cout<<"\n enter a character and enter to exit: ";
cin>>c;
return 0;
}

这是一个带有记录的示例文本文件。

aRecord 90 90 90 90 22.5
bRecord 96 90 90 90 23.9
cRecord 87 90 100 100 19.9
dRecord 100 100 100 100 25.5
eRecord 67 34 78 32 45 13.5
fRecord 54 45 65 75 34 9.84
gRecord 110 75 43 65 18.56

【问题讨论】:

标签: c++ search text


【解决方案1】:

注意,getline(myfile, line) 可能会失败,因此在这种情况下使用 line 的值是不正确的:

while (myfile.good())
{
    getline(myfile, line);
    cout << line << endl;
}

应该是:

while (getline(myfile, line))
{
    cout << line << endl;
}

对于您的问题 2 和 3:在寻求帮助之前,您应该自己尝试一些事情。如果不是解决方案,甚至不是尝试,那么您至少应该对此有一些想法。每次您想从中检索一些数据时,您都想浏览您的文本文件吗?一次读取并将其存储在内存中不是更好吗(可能是std::vector&lt;Record&gt;,然后在记录向量中搜索记录)?你想逐行浏览你的文件并在每一行中搜索一些特定的字符串吗?...只要想一想,你就会找到问题的答案。

【讨论】:

  • 感谢您的意见。我对 C++ 不熟悉,我对这种编程语言真的很陌生,即使像他们所说的那样基本。我已经考虑了很多,并尝试了不同的变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
相关资源
最近更新 更多