-2

I keep getting segmentation fault core dumped error when trying to read a text file and store it in a string, is there a way in C++ where I can store it in a string without using vectors?

void readMazeStdin2(Maze maze) {
    std::string x = " ";
    char c;

    while (!cin.eof()) {
        c = std::cin.get();
        if (c == '.' || c == '=' || c == 'S' || c == 'E') {
            x += c;
        }
        cout << c;
    }
    cout << x;
}


Jaykch
  • 103
  • 6
  • 1
    That code does not core dump, it's not correct but it does not core dump. You have a problem elsewhere. Your code that appends characters to your string is correct. Your method of detecting the end of file is wrong however. – john Mar 31 '20 at 06:23
  • 1
    When you fix the crash, read it [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – 273K Mar 31 '20 at 06:25
  • 1
    you do not read in a file except you redirect stdin, out of that if you have a seg fault this is not in that part of code. Flush the output (*cout << endl;* ) to see you finish to execute that function, and probably do also before to output *x* else result not readable. Better not use *cin.eof* do *while ((c = std::cin.get()) != EOF)* – bruno Mar 31 '20 at 06:25
  • 1
    Please show a [mre] – Alan Birtles Mar 31 '20 at 06:25

1 Answers1

0

Changing it to

while(cin>>n)

worked, thanks for the link S.M.

Jaykch
  • 103
  • 6