简体   繁体   中英

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;
}

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.

Your result vector is empty, therefore this

while(result.at(i)!=1){

Will throw out_of_range exception and cause your program to terminate.

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