我正在为我的C++课程编写一个程序。最终,我希望我的程序可以对以下格式的联系人文本文件执行快速排序:
名字 姓氏 号码
每个联系人由一个新行分隔。我已经开始计算行数并使用动态内存分配创建了一个结构体数组,其大小与行数相同。
然而,当我尝试从文本文件中读取信息并将其输出到屏幕时,我只得到了一些乱码。我在互联网上查找解决方案,但是我发现所有的例子都使用不同于我的语法。
以下是我目前的代码:
名字 姓氏 号码
每个联系人由一个新行分隔。我已经开始计算行数并使用动态内存分配创建了一个结构体数组,其大小与行数相同。
然而,当我尝试从文本文件中读取信息并将其输出到屏幕时,我只得到了一些乱码。我在互联网上查找解决方案,但是我发现所有的例子都使用不同于我的语法。
以下是我目前的代码:
#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()
std::string
变量打开文件时,请使用std::string::c_str()
方法。I/O流文件具有需要C风格字符串的构造函数。这在最近的C++版本中已经得到修复。 - Thomas Matthews