【问题标题】:Reading a string from file c++从文件 c++ 中读取字符串
【发布时间】:2014-01-21 01:57:07
【问题描述】:

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

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

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

【问题讨论】:

  • 不是编译器在读取这些单词,而是可执行文件(您的程序)在执行它。
  • 嗯。谢谢 Barak Manos。

标签: c++ string file-handling


【解决方案1】:

您可以使用类似的方法将整个文件读入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();
}

【讨论】:

    【解决方案2】:

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

    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::getline(nameFileout, item_name)
      

      而不是

      nameFileout >> item_name
      

      您可能会考虑重命名 nameFileout,因为它不是名称,并且用于输入而不是输出。

      【讨论】:

      • 感谢您帮助我。我使用名称是因为我使用该文件作为产品名称。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多