how to skip an input value?

I have a simple code, written below. I wish to skip/or not interested to enter the value of "a" at command prompt, how should I do this.

#include <iostream>
#include <istream>

using namespace std;

int main ()
{
double a, b, c;
// a = 5.5;
// b = 4.5;


std::cout << "enter value of a = ";
std::cin >>a;
/* I wish to enter here a command like in MatLab
if (isempty) {
a= 5;} */

std::cout << "enter value of b = ";
std::cin >> b ;
c = a + b;
std::cout << "value of c is ";
std::cout << c <<"\n";
system ("PAUSE");
return 0;
}

regrads

ali haider
Make 'a' an std::string, get the data into that, then check to see if it is empty or not.
cin is a very smart object.. it already can everything you need. Here is a sample:

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
#include <iostream>

int main()
{
	using namespace std;
	double a,b,c;
	cin.unsetf(ios_base::skipws); // do not skip leading whitespace

	cout << "Enter value of 'a': ";
	// the '>>' always returns a cin object, which will be converted
	// into a boolean using cin.good(). It indicates if an error happened.
	if (!(cin >> a)) {
		cin.clear(); // we have to clear error flags.
		a = 5; // set default value
	}
	while (cin.get() != '\n'); // now remove all unpleasent input

	cout << "Enter value of 'b': ";
	if (!(cin >> b)) {
		cin.clear();
		b = 5;
	}
	while (cin.get() != '\n');

	cout << "a + b = " << (c = a + b) << endl;
	return 0;
}


alternativly you could do something like this.

1
2
	cin >> a;
	if (!cin.good()) { ... }


Just look in the web for cin error handling. The cin object does following things if an error happened (f.e. if you type an unexpected character for integer input):

Value a is left unchanged
The input is left in input queue
An error flag is set
Last edited on
I've tried your suggestion, but could not get any positive result.\

actually, i wish to do :

if an input value is asked by the user, and he just press "Enter" key, the program must ask the next input value and use the default set value for that input.

please help me out.

Regards
The solution suggested by maikel is perfectly well. It works exactly as the problem said. alihaider, you should check it out or specify what you want.
Topic archived. No new replies allowed.