Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a string from file c++

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();
like image 223
user3139551 Avatar asked Jan 03 '14 11:01

user3139551


2 Answers

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();
}
like image 186
BullyWiiPlaza Avatar answered Sep 18 '22 20:09

BullyWiiPlaza


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.

like image 41
Mike Seymour Avatar answered Sep 17 '22 20:09

Mike Seymour