The basic difficulty you are having is understanding the nature of an input stream.
The input (and I think you know this) is nothing more than a stream of characters. For example:
1 + 2 * 3
This can be represented as a string or array or any ordered collection of characters:
{ '1', ' ', '+', ' ', '2', ' ', '*', ' ', '3' }
"1 + 2 * 3"
etc
The trick is that
cin
knows how to do
formated extraction: it knows how to read the
string "72"
as the
integer 72
, etc.
In order to properly parse the stream, you must consider which operation to apply to extract the next character(s).
To help with this task, google around "recursive descent parser" and you'll find examples of basic arithmetic expression parser. The idea is to have an idea of what kind of characters to expect next.
As to your question about the blanks, it is because your loop is mal-formed. Don't worry -- it is a common mistake -- but you must always check for EOF
immediately after an attempt to read,
before your code does anything with the (possibly failed-to-read) data.
1 2 3 4 5 6 7 8 9 10 11 12
|
while (true)
{
// attempt to get data
cin.get( c );
// if failure (such as EOF) then quit the loop
if (!cin) break;
// (data read successfully)
// do something with data
}
|
The C++ iostreams provide a convenient shortcut for that when inputting homogeneous data. For example, if you know your input is a space-separated list of integers, you can easily use a pretty loop like this:
1 2 3 4 5 6
|
int sum = 0;
int x;
while (cin >> x)
{
sum += x;
}
|
...which is exactly equivalent to:
while ((cin >> x).good()) // attempt to read x; continue only if no failure
{
sum += x;
} |
Likewise, you can read entire lines with the
getline() function, because
getline() returns the istream:
1 2 3 4 5 6
|
string s;
while (getline( cin, s ))
{
// s was successfully obtained
...
}
|
But, when you are reading heterogeneous data, such as parsing an algebraic expression, you really can't use the simple loop -- you'll need to use the more complex variety.
Hope this helps.