0

Writing a program that reads a set of strings into an array, and takes all the characters until whitespace occurs. Also, the strings are being read from the last to the first one from the array. My output looks really strange when I compile the code and read the output text file. Is there an error within the code here?

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

    string substring(string a, int b, int c) {
        string result = "";
        for(int i = b; i<b+c; i++) {
            result+=a[i];
        }
        return result;
    }

    int main() {
        ifstream in_stream("HW3Test.txt");
        ofstream output_stream("HW3output.txt");

        string result[100];
        int i=0;
        while(!in_stream.eof()) {
            getline(in_stream, result[i]);
            i++;
        }
         for(int j = i; j>=0; j--) {
            int counter1 = 0;
            while(result[j][counter1]!=' ') {
                 counter1++;
            }
            output_stream<<substring(result[j], 0, counter1);
            }

        output_stream.close();
        in_stream.close();
        return 0;
    }
Andrew
  • 31
  • 5
  • first, and heres a clue. I dont have you file and the program doesnt say anything, it just loops forever. Anyway what should the input look like – pm100 Mar 09 '22 at 02:34
  • 1) [Read this](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). 2) You make no check to see if there are 100 strings or less. 3) This entire exercise can be done much more easily using `std::stringstream`. This code is way too much to just read strings into an array. – PaulMcKenzie Mar 09 '22 at 02:34
  • 1
    The `while (!in_stream.eof()` loop is a fault. If the `getline()` call encounters end of file, `i` will still be incremented, so the next loop (on the first iteration) will access `result[i]` which is unchanged. from when it is declared. The `while(result[j][counter1]` loop will then have undefined behaviour. – Peter Mar 09 '22 at 02:37
  • when it reads a file with 3 lines it ends up with i = 3 becuase you dont do eof detection correctly. YOu then try to access `result[3][1]` - this doesnt exist – pm100 Mar 09 '22 at 02:41

0 Answers0