Heatherfield
Heatherfield

Reputation: 185

std::cin while loop gives a strange result

As of late, I've been doing a complete review of C++ and came across a code snippet containing the following:

#include <iostream>
using namespace std;
int main() 
{
  int a, b;
  while (cin >> a)
  {
    b+=a;
  }
  cout << b << endl;
  return 0;
}

The code snippet seems very straightforward: it puts input from the console into a and adds this onto b, for as long as valid input is presented. However, whenever I try to run this program with an input of integers, seperated with spaces, it gives a very large negative integer (-1218019327 being the most recent result, when the entire input only consisted of the number '1'). Only when I modify the code does it give correct output:

#include <iostream>
using namespace std;
int main() 
{
  int a, b;
  while (cin >> a)
  {
    cout << a << endl;
    b+=a;
  }
  cout << b << endl;
  return 0;
}

Why does adding a cout statement change the result of my code so thouroughly (yet positively)?

Upvotes: 1

Views: 78

Answers (2)

Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

You have to initialize b=0;. Or b will give you garbage value.

#include <iostream>
using namespace std;
int main() 
{
  int a, b=0;
  while (cin >> a)
  {
    cout << a << endl;
    b+=a;
  }
  cout << b << endl;
  return 0;
}

By pressing ctrl-z you will get the value of b.

Upvotes: 0

yizzlez
yizzlez

Reputation: 8805

Both programs result in undefined behavior, you did not initialize b. Try:

int b = 0;

Upvotes: 3

Related Questions