Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file into string. C++ ifstream [duplicate]

Tags:

c++

ifstream

void docDB(){
     int sdb = 0;
     ifstream dacb("kitudacbiet.txt");
     if(!dacb.is_open())
         cout<<"Deo doc dc file"<<endl;
     else{
          while(!dacb.eof()){
               dacb>>dbiet[sdb].kitu;
               dacb>>dbiet[sdb].mota;
               //getline(dacb,dbiet[sdb].mota);
               /*
               string a="";
               while((dacb>>a)!= '\n'){
                //strcat(dbiet[sdb].mota,a);
                dbiet[sdb].mota+=a;
               }
               */
               sdb++;
          }
     }

}

Text file: "kitudacbiet.txt"

\ Dau xuyet phai
@ Dau @
# Dau #
$ Ky hieu $
( Dau mo ngoac
) Dau dong ngoac

Screen

I want read firt string of line into dbiet[sdb].kitu and the rest of line into dbiet[sdb].mota

Example: line 1 = \ Dau xuyet phai

dbiet[sdb].kitu = "\" and dbiet[sdb].mota = "Dau xuyet phai"

I would like to read line by line until i met downline character ('\n'). How to do this. Sorry my english not good.Thank

like image 684
bulubuloa Avatar asked Nov 25 '12 14:11

bulubuloa


2 Answers

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

like image 70
111111 Avatar answered Oct 23 '22 03:10

111111


It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}
like image 31
Benjamin Lindley Avatar answered Oct 23 '22 04:10

Benjamin Lindley