Search code examples
c++text-filesifstreamofstreamdev-c++

Copy .txt to int array, then save into another file


// Edit : I've discovered my mistake. Still I'm missing 1 thing: It doesn't count lines correctly. If the last char in .txt isnt '\n' it counts 1 less line. If I hit it it counts 2 much. What's wrong ? Can you help me?

krol.txt =

2 4
3 7
3 13
2 4
3 1 

and main.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(){
    ofstream outFile;
    ifstream fin;
    fin.open("krol.txt");
    int l=0;
    char ch;
    while (fin.good()){
        fin.get(ch);
        if (ch=='\n') l++;
    }
    cout << l;
    fin.close();
    fin.open("krol.txt");
    int temp[l][2];
    int savel=l;
    l=0;
    int i=0;
        while (fin >> (temp[l][i])){
        i++;
        if(i==2){ 
         i=0; l++;
        }
    }

    outFile.open("save.txt");
    for (int i=0, j=0;j<savel;i++){
        if (i==2) {
        i=0; j++;
        }
        outFile << temp[j][i];
    }
    outFile.close();
    system("PAUSE");
    return 0;
     }

Solution

  • I'm no C++ expert, but shouldn't

    fout >> ch;
    

    be

    fout << ch; 
    

    ?

    (Fixed from Thomas Matthews' comment)