QuestionNew at coding (C++)

Posts 1–3 of 3 · Page 1 of 1
New at coding (C++)
Currently following a book to get a bit of an introduction towards coding / C++ stumbled upon this exercise:

Exercise 1.6: Explain whether the following program fragment is legal:

Code:
std::cout << "The sum of " << v1;
                         << " and " << v2;
                         << " is " <<  v1 + v2 << std::endl;
If the program is legal, what does it do? If the program is not legal, why
not? How would you fix it?

I got the program to work and tell me what the sum is of v1 + v2 in following code.




Code:
#include <iostream>
int main()
{
	int v1 = 3, v2 = 9;
	std::cin >> v1 >> v2;
		std::cout << "The sum of " << v1
	<< " and " << v2
	<< " is  " << v1 + v2 << std::endl;

	return 0;
}
'

Altough i first have to press a random letter/symbol and enter before it shows me the sollution of 3 + 9, Anyone knows why it does that?

I'm using Visual studio 2017

Thanks.


EDIT

I figured out line 5: std::cin >> v1 >> v2; was causing it because it reads the input. Why is that in this situation?
you need propably std::cin.clear(); to flush the buffer from cin
and the code is "legal" if u don't print too much with that.
std::endl; flushs the buffer too so use "\n" until you want print the last line, because cout writings are slow
std::cin is used to read input, so you're reading into v1 and v2.
In the code sample the semicolons at the end of each line is what's wrong.
Posts 1–3 of 3 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us