从文件中读取字符串 c++

12

我正在尝试为我父亲的餐馆制作一个计费系统,只是为了练习。问题在于程序不能一次读取完整的字符串,例如如果txt文件中有“鸡肉汉堡”,编译器会读取它们但会将其分成两个单词。我正在使用以下代码,文件已经存在。

std::string item_name;
std::ifstream nameFileout;

nameFileout.open("name2.txt");
while (nameFileout >> item_name)
{
    std::cout << item_name;
}
nameFileout.close();

1
不是编译器在读取这些单词,而是可执行文件(您的程序)在执行此操作。 - barak manos
3个回答

13

要读取整行,使用

std::getline(nameFileout, item_name)

而不是

nameFileout >> item_name

由于nameFileout不是一个名称,而是用于输入而不是输出,因此您可能需要考虑更改其名称。


1
感谢您的帮助。我使用名称是因为我正在将该文件用于产品名称。 - user3139551

6

逐行读取并在内部处理每一行:

string item_name;
ifstream nameFileout;
nameFileout.open("name2.txt");
string line;
while(std::getline(nameFileout, line))
{
    std::cout << "line:" << line << std::endl;
    // TODO: assign item_name based on line (or if the entire line is 
    // the item name, replace line with item_name in the code above)
}

3
您可以使用以下代码将整个文件读入std::string中:
std::string read_string_from_file(const std::string &file_path) {
    const std::ifstream input_stream(file_path, std::ios_base::binary);

    if (input_stream.fail()) {
        throw std::runtime_error("Failed to open file");
    }

    std::stringstream buffer;
    buffer << input_stream.rdbuf();

    return buffer.str();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接