Search code examples
c++vectorstreamtext-filesfstream

Reading int from .txt , save it to vector and then save to output file


I've written a mysterious program that it suppose to open and read this .txt

`> krol.txt

3 7
3 13
2 4
3 1

and then save it to vector, do some crazy operation with some algorithms, save it to another vector and stream it into file. But crazy thing are going after running .exe. it doesn't show anything, nothing happens. No errors during compiling and... yeah. idk what went wrong. got any idea about what's wrong?

#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
using namespace std;
int nwd (int a,int b);
int main(){
    ifstream fin;
    fin.open("krol.txt");
    if (!fin) cout << "WTF" << endl;
    system("PAUSE");
    vector<int> tab;
    int i=0;
    int n=0;
    while (fin>> i){
        tab.push_back(i);
    }
    fin.close();
    vector<int> result;
    bool right=false;
    ofstream outFile;
    outFile.open("save.txt");
    i=0;
    result.at(0)=tab.at(0);
    while(result.at(i)!=1){
        if (right){
            result.push_back(tab.at(i+2));
        }
        else if (nwd(result.at(i),tab.at(i+2))==1) result.push_back(tab.at(i+2));
        else {
            result.push_back(tab.at(i+1)); right=true;
        }
        outFile << result.at(i) << " " ;
        i++;
    }
    outFile.close();
    return 0;
}
int nwd(int a,int b){
    while (a!=b){
        a>b ? a-=b : b-=a;
    }
    return a;
}

Solution

  • I think I got it. You need to change the code while(result.at(i)!=1){ to this one while(tab.at(i)!=1){. That's just a little bug.