For example, I need to accept the dimensions of two rectangles on different lines.
I tried it this way:
int a1, b1, a2, b2;
char c;
cin >> a1 >> b1;
cin >> c >> a2 >> b2;
For example, I need to accept the dimensions of two rectangles on different lines.
I tried it this way:
int a1, b1, a2, b2;
char c;
cin >> a1 >> b1;
cin >> c >> a2 >> b2;
So you want the user to enter those 4 integers in this fashion:
-10 0
30 40
And you want to reject all other formats of input...
In other words, the input must include:
4 int
integers
2 ' '
spaces
2 '\n'
newlines
You can modify the logic I'm going to discuss to tweak those parameters as necessary.
This is more like a problem solving task. Anyways, since you don't want to use getline
for some reason, you will have to manage most of the input processing yourself.
Here is my take on this:
Read the input character (char ch
) by character until you receive four separate (separated by either a space or a newline) inputs (could be anything including void, validation can be done afterwards). Use std::stringstream
(stringstream input
) to read the entire input; it will make input validation easier as we proceed. Have two variables (unsigned spaceCount = 0;
and unsigned newlineCount = 0;
) to control the loop termination.
while (newlineCount + spaceCount != 4)
{
ch = cin.get();
input << ch;
if (ch == ' ')
++spaceCount;
if (ch == '\n')
++newlineCount;
}
Before proceeding, you need a function like bool isInt(string num)
to check whether a given string is an integer or not. You can make one yourself according to your needs. Stackoverflow already has a thread on this: How to determine if a string is a number with C++? The function must return true only if the string can be fit into an int
.
Then you can check the user-input for hidden gems, non-inputs or spam:
bool inputFormatCorrect = true;
if (spaceCount == 2 && newlineCount == 2)
{
stringstream tmpInput;
string tmpStr;
tmpInput << input.str();
for (int i = 0; i < 4; ++i)
{
tmpInput >> tmpStr;
if (!isInt(tmpStr))
{
inputFormatCorrect = false;
break;
}
}
}
else
{
inputFormatCorrect = false;
}
Once the checking is complete, you can extract and display your integers (int a1, b1, a2, b2;
):
if (inputFormatCorrect)
{
input >> a1 >> b1 >> a2 >> b2;
cout << "a1 = " << a1 << ", b1 = " << b1 << ", a2 = " << a2 << ", b2 = " << b2;
}
else
{
cout << "I don't like your style of inputting...";
}
Putting it all together: Live Demo
And I'm not really sure if you want the restriction on spaces as well, but you can modify the logic to remove all occurrences of spaceCount
and change the read loop condition to while (newlineCount != 2)
if required.
So, did you really mean to make things complicated? There's a reason why we have standard input.
I would still prefer
cin >> a1 >> b1 >> a2 >> b2;
Instead of giving the user a tough time: