-3

I am practicing for reading in a file and editing the contents. The input would be something like:

2 2 3 -1

3 3 -1 3  

I want to make the -1's nothing. It works for the first line so I get:

2 2 3 

3 3 -1 3  

But as you can see, on other lines it does not edit. What is wrong with my loop? I am new to C++ so I am confused. Also, english is not my first language so sorry for any mistakes!

if (fin.is_open())
        {
          while ( getline (fin,line) )
            {
              for (int i; i<line.size(); i++){
                if(line[i] == '-'){
                  line[i] = ' ';
                  line[i+1] = ' ';
                }
              }
              cout << line << '\n';
            }
          fin.close();
        }
Ryan Riis
  • 13
  • 5
  • 1
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Oct 04 '18 at 18:22
  • `line[i+1]` might do out of bound access. – Jarod42 Oct 04 '18 at 18:22
  • This doesn't address the question, but `if (fin.is_open())` is redundant; the call to `getline` will fail if the stream isn't open. And the call to `fin.close()` isn't needed. The destructor will do that. – Pete Becker Oct 04 '18 at 18:46

1 Answers1

2

Your code has undefined behavior due to use of uninitialized i in the for loop.

Change the line to

for (int i = 0; i<line.size(); i++){
//           ^^ Need that
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • @RyanRiis, Feel free to beat yourself up but such mistakes are not uncommon when you are learning the language. – R Sahu Oct 04 '18 at 19:18