【发布时间】:2017-07-21 17:29:53
【问题描述】:
我正在尝试读取一个文件,其中第一行是整数,下一行是字符串(我必须将其读入 char 数组)。 我在输入流对象上使用 >> 运算符来读取整数,然后我使用 .get() 方法和 .ignore() 方法将下一行读入 char 数组,但是当我尝试读入char 数组我得到一个空白字符串 我不知道为什么我得到一个空白字符串,你知道为什么会这样吗?
这是我用来从文件中读取的代码:
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 字符串是空白的。为什么?
【问题讨论】:
-
想想第一行的整数之后的第一个
\n。 -
提供示例文件?
-
你为什么不用
getline()?