2012-10-09 136 views
0

好的,即时通讯新的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 
+0

@Radu无关紧要,如果它是作业:[家庭作业标签现在正式弃用](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially -deprecated) – slugster

回答

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<Record>然后搜索记录向量中的记录)是不是更好?你是否想逐行浏览你的文件,并在每一行中搜索一些特定的字符串?...只要仔细想一想,你就会找到你的问题的答案。

+0

感谢您的意见。我不是C++中的经文,我真的对这种编程语言很陌生,即使他们说的是基本的。我一直在给它很多的想法,并尝试不同的变化。 – user1733201