从C++中读取文件的麻烦
问题描述:
我想读取一个文件,其中第一行是一个整数,并且下一行是一个字符串(我必须将其读入char数组)。 我在输入流对象上使用了>>运算符来读取整数,然后我使用.get()方法和.ignore()方法将下一行读入char数组,但是当我尝试读入字符数组我得到一个空字符串 我不知道为什么我得到一个空白字符串,你知道为什么这可能是?从C++中读取文件的麻烦
这里是我使用从文件中读取的代码:
BookList::BookList()
{
//Read in inventory.txt and initialize the booklist
ifstream invStream("inventory.txt", ifstream::in);
int lineIdx = 0;
int bookIdx = 0;
bool firstLineNotRead = true;
while (invStream.good()) {
if (firstLineNotRead) {
invStream >> listSize;
firstLineNotRead = false;
bookList = new Book *[listSize];
for (int i = 0; i < listSize; i++) {
bookList[i] = new Book();
}
} else {
if (lineIdx % 3 == 0) {
char tempTitle[200];
invStream.get(tempTitle, 200, '\n');
invStream.ignore(200, '\n');
bookList[bookIdx] = new Book();
bookList[bookIdx]->setTitle(tempTitle);
} else if (lineIdx % 3 == 1) {
int bookCnt;
invStream >> bookCnt;
bookList[bookIdx]->changeCount(bookCnt);
} else if (lineIdx % 3 == 2) {
float price;
invStream >> price;
bookList[bookIdx]->setPrice(price);
bookIdx++;
}
lineIdx++;
}
}
}
所以LISTSIZE是从该文件的第一行读取的第一整数,tempTitle是用于读取的临时缓冲器在文件第二行的字符串中。但是当我做invStream.get()和invStream.ignore()时,我看到tempTitle字符串是空的。为什么?
答
你可以最有可能通过交换线路修复程序
invStream.get(tempTitle, 200, '\n');
invStream.ignore(200, '\n');
即使用:
invStream.ignore(200, '\n');
invStream.get(tempTitle, 200, '\n');
作为一般原则,如果一个文件的内容格式,使得线文本具有特定含义,您将更容易逐行读取文件的内容并处理每行的内容。
std::string line;
while (getline(invStream, line)) {
if (firstLineNotRead) {
// Extract the listSize from the first line using
// a istringstream.
std::istringstream str(line);
str >> listSize;
firstLineNotRead = false;
bookList = new Book *[listSize];
for (int i = 0; i < listSize; i++) {
bookList[i] = new Book();
}
}
else {
// The line has already been read.
// Use it.
...
}
}
答
从文件读入第一个整数后,等待读取的文件中有一个换行符。
然后继续告诉它读取一个字符串。它这样做 - 将新行解释为字符串的结尾,所以您读取的字符串是空的。在这之后,一切都变得不可思议了,所以其余的阅读都保证不成功(至少不能达到你想要的)。
顺便说一句,我会去这样的任务而不同 - 可能更是这样的:
#include <iostream>
#include <vector>
#include <bitset>
#include <string>
#include <conio.h>
class Book {
std::string title;
int count;
float price;
public:
friend std::istream &operator>>(std::istream &is, Book &b) {
std::getline(is, title);
is >> count;
is >> price;
is.ignore(100, '\n');
return is;
}
};
int main() {
int count;
std::ifstream invStream("inventory.txt");
invStream >> count;
invStream.ignore(200, '\n');
std::vector<Book> books;
Book temp;
for (int i = 0; i<count && invStream >> temp;)
books.push_back(temp);
}
想想第一个'\ N'按照您在第一行的整数。 –
提供样本文件? – everettjf
为什么不使用'getline()'? –