Home > Net >  Why do I keep getting a zsh: segmentation fault error when I use a.out for this file?
Why do I keep getting a zsh: segmentation fault error when I use a.out for this file?

Time:03-08

New to file io in c . I'm initially writing a basic program to simply remove comments from a file. If the first two characters are //, then I basically need to skip and print the following line in the text file. My output file and input file are both in the same folder as my CPP file, so I'm not sure why I keep getting an error here.

    #include <iostream>
    #include <stream>
    using namespace std;

    int main() {
        ifstream in_stream("HW2Test.txt");
        ofstream output_stream("HW2output.txt");

        string result[100];
        int i;
        while(!in_stream.eof()) {
            in_stream>>result[i];
            i  ;
        }
         for(int j = 0; j<i; j  ) {
            if((result[j][0]=='/')&&(result[j][0]=='/')) {
                 output_stream<<result[j 1];
            }
        }
        output_stream.close();
        in_stream.close();
        return 0;
    }

CodePudding user response:

Your variable int i is not initialized, so in_stream>>result[i] yields undefined behaviour.

Use int i=0 instead (and check if i < 100 before writing to your buffer).

  • Related