Read text file into string. C++ ifstream

bulubuloa picture bulubuloa · Nov 25, 2012 · Viewed 99.5k times · Source
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

Answer

111111 picture 111111 · Nov 25, 2012

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