Home > Net >  how to get full text from a txt file to a string variable in c ? I tried normally, but it terminate
how to get full text from a txt file to a string variable in c ? I tried normally, but it terminate

Time:11-16

I have a file named "lio.txt" with text, "my name is bio". I want to shift the full line to a string variable. How can I do that?

CodePudding user response:

this code should do it (error checking is ommited):

std::string read_all_file()
{
    std::ifstream file{ "file.txt", std::ios::ate }; // open the file and set the get position to the end
    std::string buff;
    buff.resize(file.tellg()); // the get position is the file size
    file.seekg(0, file.beg); // seek to the begin of the file to start reading
    file.read(buff.data(), buff.size()); // read the whole file in buff
    return buff;
}

CodePudding user response:

 This program takes text strings in separate lines and stores them in myText variable.

#include <iostream>
#include <string>
#include <fstream>     

using namespace std;

int main () {

    ifstream file("lio.txt");
    string myText;  
       
    while (getline(file, myText)) 
    {
        cout << myText << endl;
    }

    return 0
}

my name is bio

  • Related