Pergunta

I'm trying to make billing system for my father's restaurant just for practice. The problem is that the program doesn't read the complete string one time.e.g If there were "Chicken burger" in txt file then the compiler reads them but break them into two words. I'm using the following code and the file is already exist.

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

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

Solução

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.

Outras dicas

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

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();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top