c++ - 在 C++ 中读取文件时遇到问题

标签 c++ string file io

我正在尝试读取一个文件,其中第一行是一个整数,下一行是一个字符串(我必须将其读入一个字符数组)。 我在输入流对象上使用 >> 运算符读取整数,然后使用 .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 字符串为空。为什么?

最佳答案

从文件中读取第一个整数后,文件中有一个新行等待读取。

然后您继续告诉它读取一个字符串。它是这样做的——将换行符解释为字符串的结尾,因此您读取的字符串是空的。

在那之后,一切都乱套了,所以剩下的阅读几乎肯定会失败(至少不能达到你想要的)。

顺便说一句,我会以完全不同的方式完成这样的任务——可能更像这样:

#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);
}

关于c++ - 在 C++ 中读取文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547801/

相关文章:

arrays - 将字符串拆分为数组并对每个字符 Swift 执行特定操作

c# - C#中的大写句子

python - 我如何使用Python查找目录中是否有任何txt文件

c++ - 你如何使用 string.erase 和 string.find?

c++ - 如何防止使用 ofstream 覆盖文本文件中的信息?

android - 访问我的 strings.xml 项目时出现问题......我得到的是数字而不是字符串值

java - 如何在 Android 上创建和/或附加到文件?

Perl 脚本使前 8 个字符全部大写,但不是整个文件名

c++ - C++中的迷宫求解算法

c++ - 如何正确设计工作线程? (例如避免 sleep (1))