May someone help me with my code?

Why this code doesnt work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string mystr;
  int a;
  cout << "What's your name? ";
  getline (cin,mystr);
  cout << "Hello " << mystr << ".\n";
  cout << "How old are you?";
  getline (cin, mystr);
  stringstream(mystr) >> a
  
  if (a > 16)
  {
  	 cout << "You are older than me." << endl << "I am 16 years old.";
  }
  
  else if (a < 16)
  {
  	cout << "You are younger than me." << endl << "I am 16 years old.";
  } 
  
  else
  {
  	 cout << "I am 16 years old too."; 
  }
  
  
  return 0;
}
Last edited on
There are some syntax errors. Have you checked the compiler's output?
It would also be much easier to use cin instead of getline.
You don't need sstream. Just replace lines 14 and 15 with:

cin >> a;
ok I know that cin is easier than getline but anyway it doesnt run and it´s not beacuse it seays getline instead of cin. It says else without a previous if AND THERE IS A PREVIOUS IF!
just do

if ( a > 16 )
{
// code
}

if( a < 16 )
{
code
}

else
{
// code
}

I'm pretty sure ( not 100% ) but pretty sure that else has to directly follow an if statement, not an else if statement...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
	string mystr;
	int a;
	cout << "What's your name? ";
	getline(cin, mystr);
	cout << "Hello " << mystr << ".\n";
	cout << "How old are you?";
	getline(cin, mystr);
	stringstream(mystr) >> a; // <<-- You also missed a ';' here that I kindly added :)

		if (a > 16)
		{
			cout << "You are older than me." << endl << "I am 16 years old.";
		}

		if (a < 16)
		{
			cout << "You are younger than me." << endl << "I am 16 years old.";
		}

		else
		{
			cout << "I am 16 years old too.";
		}


		system("pause");
		return 0;
}



system("pause") // because I run my code in the console and it's habitual lol
Last edited on
That ';' I dindnt see it
PD: else if works better than just if
Topic archived. No new replies allowed.