我正在爲我的C++類做一個程序。最後,我想我的程序上按以下格式的聯繫人的文本文件進行快速排序:將信息讀入結構數組C++
姓Secondname數
每接觸一個新行分離。我已經開始計算行數並使用動態內存分配來創建一個與行數相同大小的結構數組。
但是,當我試圖讀取文本文件中的信息並將其輸出到屏幕上時,我所得到的只是亂碼。我在互聯網上看了一遍,試圖找到一個解決方案,但是我發現的一切似乎都對我使用了不同的語法。
這裏是我到目前爲止的代碼:
#include <iostream>
#include <fstream>
#include <istream>
char in[20];
char out[20];
using namespace std;
struct contact
{
char firstName[14];
char surName[14];
char number[9];
};
//structure definition
int main(void){
cout << "Please enter the input filename: " << endl;
cin >> in;
ifstream input(in);
if(!input){
cerr << "failed to open input file " << in << endl;
exit(1);
}
cout << "Please enter tne output filename: " << endl;
cin >> out;
// read in the input and output filenames
char a;
int b=0;
while (input.good())
{
a=input.get();
if (a=='\n')
{
b++;
}
}
// count the number of lines in the input file
input.seekg (0, ios::beg);
//rewind to beginning of file
contact* list = new contact[b];
//dynamically create memory space for array of contacts
int i = 0.;
while(input){
if(i >= b) break;
if(input >> *list[i].firstName >> *list[i].surName >> *list[i].number) i++;
else break;
}
input.close();
//read information from input file into array of contacts
for(int N = 0; N < b; N++){
cout << list[N].firstName << list[N].surName << list[N].number << endl;
}
ofstream output(out);
int k = 0;
for(int k = 0; k<b; k++){
output << list[k].firstName << " " << list[k].surName << " " << list[k].number << endl;
}
//print out the unsorted list to screen and write to output file
//i've done both here just to check, won't print to screen in final version
output.close();
delete []list;
} // end of main()
我敢肯定你需要刷新輸入流,因爲它已經到達文件的末尾,給對象的值爲false。你也有一些使用input.get的低效方法,當你只需要一次抓一行直到文件結尾 –
你是什麼意思通過刷新輸入流?我以爲seekg會將編譯器帶回到文件的開頭? – GGled
是的,但是當你計算行數時,你的文件已經達到一次eof。文件標誌被設置爲FALSE以顯示它處於eof,但將讀取器設置回零不會刷新此標誌 –