从C 中的文件阅读麻烦
trouble reading from file in c++
我正在尝试读取第一行是整数的文件,而下一行是字符串(我必须将其读取到一个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++;
}
}
}
SO ListSize是第一个从文件中的第一行读取的整数,而Temptitle是一种临时缓冲区,用于从文件的第二行中读取字符串。但是,当我做Invstream.get()和Invstream.ignore()时,我看到Temptitle字符串为空白。为什么?
从文件中读取第一个整数后,文件中有一个新线等待读取。
您然后继续告诉它阅读字符串。它这样做 - 将新线解释为字符串的末端,因此您读取的字符串为空。
之后,一切都超出了Kilter,因此所有其余的阅读都可以保证失败(至少无法实现您想要的东西)。
顺便说一句,我会做些不同的任务 - 可能更像是这样:
#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);
}
您很可能可以通过交换行
来修复程序invStream.get(tempTitle, 200, 'n');
invStream.ignore(200, 'n');
即,使用:
invStream.ignore(200, 'n');
invStream.get(tempTitle, 200, 'n');
作为一般指南,如果对文件的内容进行了格式,以使文本行具有特定的含义,则您可以通过行读取文件内容并处理每行的内容的内容更容易。<<<<<<<<<</p>
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.
...
}
}
相关文章:
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- R -RCPP:链接到Shogun C 文件的麻烦
- 在C 中输出到二进制文件中的麻烦
- 在此任务上遇到麻烦,我们需要使用指针和数组来找到文本文件中某些数字的平均值,中值和模式
- C++,映射插入&&文件流读取导致麻烦
- 从C 中的文件阅读麻烦
- 将C 源文件分为多个文件的麻烦
- NeatBeans Makefile:麻烦编译.H文件
- C++处理文件,在制作程序时遇到麻烦
- 麻烦读取.txt文件
- C :将文本文件的内容存储在2D数组中,作为字符串(用于NULL终结器的麻烦?)
- C 麻烦阅读文本文件
- C++从.txt文件中读取+二进制搜索+排序;上课的麻烦
- 在使用头文件/源文件时访问类变量的麻烦
- 在c++中添加第二个.h/cpp文件时遇到麻烦
- 在使用数据结构从文件中读取数据时遇到麻烦
- 在将我写的内容输出到文件时遇到麻烦
- 从文本文件加载时遇到麻烦
- 在c++中读取.csv文件时遇到麻烦
- 麻烦输出矢量到.txt文件