cin >> if

So i'm making a simple program to keep score for a game of cricket. I'm getting stuck when it comes to inputting the players score for their turn. If the player scores regularly then it's simple cause it's just a number. but if the player hits a double or triple on the board then whatever they hit is doubled or tripled.

Example:
20 = 20 points
20d = 40 points ("d" for double)
20t = 60 points ("t" for triple)

So i wrote this for testing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"
#include <iostream>

using namespace std;


int main()
{
	int a;
	char b;

	cout << "Enter Score: "; cin >> a >> b ;
	cout << a << endl << b ;


	cout << "\n\n" ;
	system("PAUSE");
	return 0;
}


with this i can enter both an integer and a character at the same time on the same line and store them both separately as their own value.

Example:

Enter Score: 20t

int a = 20
char b = t

So here's where the problem is. If the player only scores a single 20 then i want to be able to enter "20" then press Enter and input my next score. but of course that's not going to happen since it's first going to ask me to input a character before i can input my next score. The simple solution would be to enter 20s (20 single) to satisfy both int and char, but i don't want to have to input that extra character.

What I need:
a way to input "char b" only IF i don't press the (Enter Key) after inputting "int a".

If i can make that happen then i can set "char b = 's';" and if i input 20 then press (Enter Key) it will skip "cin >> b;" and "char b" will be by default 's'. but if i input 20t or 20d then it wont skip anything.

1
2
3
4
5
6
7
8
9
10
int a;
char b = 's';

cin >> a;
if (don't press "Enter")
{
  cin >> b;
}
else 
 Continue with the reset of the program. 
Use getline and string streams.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	string s;
	getline(cin, s);
	
	stringstream ss(s);
	
	int a;
	char b='s';
	
	ss>>a;
	if(ss.good()) ss>>b;
	
	cout<<a<<' '<<b<<'\n';
}


Hope it helps.
If you change b to a string you can use std::getline instead. That will read the rest of the line. Then you can easily check if the string is empty or not.
Thanks Guys
Can't you just do something like this?
1
2
3
4
5
6
7
8
9
10
int a;
char b;

cin >> a;
b = cin.get(); // Get the next character in the input stream
// If the user pressed Enter right after the number, this will be a newline character
// Otherwise, it will be the character the user entered
if (b == '\n')
    b = 's'; // Set to default value
// Continue with the rest of the program 
yeah that works but i'm new and didn't know i could do that. Thanks
Topic archived. No new replies allowed.