读取一个txt文件显示异常
Display abnormal for read a txt file
我写了一些代码 below.The title
和 authors
类型是字符数组,我无法更改 it.When 数据是从键盘输入的,结果是正常的。
void BookException::getBook()
{
cout<<"Id number: ";
cin>>booknum;
cout<<"Title: ";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.getline(title, sizeof(title), '\n');
cout<<"Authors: ";
cin.getline(authors, sizeof(authors), '\n');
cout<<"Number of pages:";
cin>>pagenum;
cout<<"Price: ";
cin>>price;
cout<<"over"<<endl;
}
下面是输入文字
1
How to program C++
Paul Deitel, Harvey Deitel
1028
112.83
但是当我尝试从 txt file.It 中读取一些文本时,显示如下:
Id number: Title: Authors: Number of pages:Price: The no. 0 book error.
Title:
Authors:
Number of pages: 0
Price: 0.00
Incorrect price.
我认为 getline
由于问题,但我不知道如何解决 it.Thank 你。
我没有看到在您的代码中传入或打开的文件。此外,在阅读变量或换行符后,您永远不会打印任何变量。使用字符串会容易得多,但如果您必须使用 char 数组,我建议编写一个函数来将 c 字符串转换为字符串并返回,请参阅:c_str().
void BookException::getBook() {
string booknum, title, authors, pagenum, price;
ifstream fin; //file in
fin.open("book.txt"); //Open the file
getline(fin, booknum); //Read line from file first
cout << "Id number: " << booknum << endl; //Then print
getline(fin, title);
cout << "Title: " << title << endl;
getline(fin, authors);
cout << "Authors: " << authors << endl;
getline(fin, pagenum);
cout << "Number of pages:" << pagenum << endl;
getline(fin, price);
cout << "Price: " << price << endl;
cout << "over" << endl;
fin.close(); //Close the file
}
我建议您阅读此内容,除非您了解所有这些内容:input/output with files
getline()
用法可参考here.
我写了一些代码 below.The title
和 authors
类型是字符数组,我无法更改 it.When 数据是从键盘输入的,结果是正常的。
void BookException::getBook()
{
cout<<"Id number: ";
cin>>booknum;
cout<<"Title: ";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.getline(title, sizeof(title), '\n');
cout<<"Authors: ";
cin.getline(authors, sizeof(authors), '\n');
cout<<"Number of pages:";
cin>>pagenum;
cout<<"Price: ";
cin>>price;
cout<<"over"<<endl;
}
下面是输入文字
1
How to program C++
Paul Deitel, Harvey Deitel
1028
112.83
但是当我尝试从 txt file.It 中读取一些文本时,显示如下:
Id number: Title: Authors: Number of pages:Price: The no. 0 book error.
Title:
Authors:
Number of pages: 0
Price: 0.00
Incorrect price.
我认为 getline
由于问题,但我不知道如何解决 it.Thank 你。
我没有看到在您的代码中传入或打开的文件。此外,在阅读变量或换行符后,您永远不会打印任何变量。使用字符串会容易得多,但如果您必须使用 char 数组,我建议编写一个函数来将 c 字符串转换为字符串并返回,请参阅:c_str().
void BookException::getBook() {
string booknum, title, authors, pagenum, price;
ifstream fin; //file in
fin.open("book.txt"); //Open the file
getline(fin, booknum); //Read line from file first
cout << "Id number: " << booknum << endl; //Then print
getline(fin, title);
cout << "Title: " << title << endl;
getline(fin, authors);
cout << "Authors: " << authors << endl;
getline(fin, pagenum);
cout << "Number of pages:" << pagenum << endl;
getline(fin, price);
cout << "Price: " << price << endl;
cout << "over" << endl;
fin.close(); //Close the file
}
我建议您阅读此内容,除非您了解所有这些内容:input/output with files
getline()
用法可参考here.