Reading a string from file c++

Read line by line and process lines internally:

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

To read a whole line, use

std::getline(nameFileout, item_name)

rather than

nameFileout >> item_name

You might consider renaming nameFileout since it isn't a name, and is for input not output.


You can use something like this to read the entire file into a 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();
}