0
votes

I'm just trying to figure out this:

I have following code:

#include <iostream>
using namespace std;

int main() {
  int n, x = 0;
  cin >> n;
  char s[3];

  while (n-- > 0) {
    cout << n << endl;
    // cin >> s;
  }

  return 0;
}

If I fill n with 2, everything works fine (1 and 0 get printed), but if I uncomment the cin >> s; line, only first iteration (1) will be performed (and the input gets saved into s).

Now my question: why is working like that? And how can I fix it? Thanks in advance.

1
Works as expected here. Try running it in a debugger.n. 1.8e9-where's-my-share m.
I ran it at: codechef.com/ide and with input: 2 (newline) X++ (newline) --XBryan Horna
@n.m. It might not run as expected, depending on input of s. It looks like classic buffer overflow, since s is only [3].Bartosz Przybylski
@bartek looks like classic buffer overflow this is expected too of course.n. 1.8e9-where's-my-share m.
How many characters do you think are in the string "X++"? Hint: not three.n. 1.8e9-where's-my-share m.

1 Answers

0
votes

Aside from the useless declaration of variable x, I think there's nothing wrong with your code.

If n is filled with 2 the result is always 1 and 0 get printed, regardless the cin >> s; is uncommented or not.