i want to read each line of my file in seprated string
what i have achieved till now is i can read the whole lines in one string
and now i want to read each line in a sprated string
any help;

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])

{
    ofstream myfile ("example.txt",ios::trunc);
    if (myfile.is_open())
    {
      myfile<<"Hossam Hassan Hossney "<<endl;
      myfile<<"20070123 "<<endl; 
      myfile<<"hossambob2003@hotmail.com "; 

      myfile.close();



    }
    else 
    cout<<"unable to open the file";

   ifstream myReadFile;
   string name;
   string temp;
   myReadFile.open("example.txt");
   char output[100];
   if (myReadFile.is_open()) {
   while (!myReadFile.eof()) {

  getline(myReadFile,name);
  cout<<name;


}
}
    system("PAUSE");
    return EXIT_SUCCESS;
}
Member Avatar for iamthwee

cin.getline()

is generally the preferred way to do this.

can you tell me by example how to use this function

Member Avatar for iamthwee

Can't test this but...

while ( getline ( read, line, '\n' ) )

Where

read is ifstream read ( "samplefile.txt" )line is a std::string

Arrays maybe?

Or better yet, vectors, since the number of lines in the file is not known during compilation.

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

using namespace std;

int main()
{
    ifstream fin("main.cpp");

    vector<string> lines;

    string curLine;

    while (getline(fin, curLine)) lines.push_back(curLine);

    for (size_t i = 0, size = lines.size(); i < size; ++ i)
        cout << lines[i] << endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.