Numbers in text file problem

Hi guys.I need to copy data from one text file to another.This is how data in file looks like:
1
2
3
4
2 -3 8 5 0
3 5 1
2 -2 3 1 7 6
5 -3 15 0 1 


I succesfully managed to copy those numbers but with one mistake.The last number is written twice.No matter what I am doing,I cant repair it.I would be really thankfull if you could help me to solve this.My output file looks like this:
1
2
3
4
2 -3 8 5 0
3 5 1
2 -2 3 1 7 6
5 -3 15 0 1 1


This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    
    int a;
    string str;
    stringstream line;

    ifile.open("input.txt",fstream::in);
    ofile.open("output.txt",fstream::out | fstream::trunc);

    while ( ! ifile.eof() )     
    {
              getline(ifile,str);
              if(ifile.eof()){
                   break
              }
              else{
                   line << str;   
                   while( !line.eof() ){
                          line >> a;
                          ofile << a << " ";
                   }
                   ofile << endl;
                   line.clear();
                   line.str(""); 
              }
          
    }

    ifile.close();
    ofile.close();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>
#include <string>

int main() // copy file "input.txt" to "output.txt"
{
    std::ifstream ifile( "input.txt" ) ;
    std::ofstream ofile( "output.txt" ) ;
    
    /* either */ std::string str ;
    while ( std::getline( ifile, str ) ) ofile << str << '\n' ;

    /* or */ ofile << ifile.rdbuf() ;
}
Sorry,I forgot to mention this,but I need to do some operations with those numbers afterwards ,that is why I copy only one character each time,not the whole string...anyway thanks for trying.
Try using fgetc(), fscanf(), sscanf(), fgets(). These all work for reading data from files
Topic archived. No new replies allowed.