简体   繁体   中英

Reading line by line and fetch word from line in C++

string line;
string filename;
cout << "Please enter filename :" << endl;
cin >> filename;
ifstream myfile(filename);
/*cout << "Please enter the name of file that you write results : "<< endl;
cin >> wfile; */
if(myfile.is_open())
{

    while(getline(myfile,line))
    {
        convert(line);

    }

    //getline(myfile,line);
    //pushintoVector(line,buffer);
}
else
{
    cout << "Error : File could not be opened" << endl;

}

try{
myfile.close();
myFile.close();
}catch(exception &e1)
{
    cout << endl;
}
//system("PAUSE");
return 0;

After that i want to send current line to another function like:

void convert(string lines)
{
    myFile.open("yazici.txt");

    string buf;
     string convertingnum;
    istringstream ss(lines);

    while(ss >> buf)
    {                

So how can i read word from a line and change it according to if-else structure and write it another file.Edit: Also is there a function or method to determine line length ?

  1. Open the output file at the same time you open the input file.
  2. Pass the output stream as an argument to convert instead of opening the file every time in the function.
  3. Use better names than myfile and myFile .
ifstream inputFile(filename);
ofstream outputFile("yazici.txt");

if(inputFile.is_open())
{
   while(getline(inputFile,line))
   {
      convert(outputFile, line);
   }
}

and ...

void convert(std::ostream& outputFile,
             string lines)
{
   string buf;
   string convertingnum;
   istringstream ss(lines);

   while(ss >> buf)
   {
       outputFile << buf << std::endl; //???
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM