Basic Input/Output Tutorial

The Basic Input/Output Tutorial found here:

http://www.cplusplus.com/doc/tutorial/basic_io/

contains this:

---------------

cin >> a;
cin >> b;


....the user is expected to introduce two values, one for variable a, and another for variable b. Any kind of space is used to separate two consecutive input operations; this may either be a space, a tab, or a new-line character.

---------------

This is wrong, isn't it? two consecutive input operations don't always need to be separated by whitespace...right?

Without whitespace how many variables can 1234 fill?

How many for 12 34?
Let's compile some real simple code and see why whitespace is needed to differentiate inputs:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
   int a { };
   std::cin >> a;

   int b { };
   std::cin >> b;

   std::cout << a << ", " << b << '\n';
}


When run enter each value separate, followed by hitting the return key (the return key enters a newline into the input stream....whitespace):
12
34
12, 34


Separate the values by a space, then enter:
12 34
12, 34

A space is whitespace

tab and enter:
12      34
12, 34

tab is whitespace

Only a comma, no other whitespace, and enter:
12,34
12, 0

Hmmmm, maybe just a comma alone isn't a good way to separate out multiple inputs.

No whitespace, and just hit enter:
1234

The program only received one value, 1234, and is waiting for another to be entered.
Whitespace isn't always needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
   int a;
   char b;

   stringstream anInputStream( "12x" );
   anInputStream >> a >> b;

   cout << "a is " << a << '\n';
   cout << "b is " << b << '\n';
}
a is 12
b is x



Not very pretty, but you could also try, for two integers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
   int a, b;

   stringstream anInputStream( "1234-5678" );
   anInputStream >> a >> b;

   cout << "a is " << a << '\n';
   cout << "b is " << b << '\n';
}
a is 1234
b is -5678



And this one is just an encouragement to make mistakes!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
   int a;
   double b;

   stringstream anInputStream( "1234.5678" );
   anInputStream >> a >> b;

   cout << "a is " << a << '\n';
   cout << "b is " << b << '\n';
}
a is 1234
b is 0.5678




For non-numeric input:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
   char a, b, c;
   
   stringstream anInputStream( "c++" );
   anInputStream >> a >> b >> c;

   cout << "a is " << a << '\n';
   cout << "b is " << b << '\n';
   cout << "c is " << c << '\n';
a is c
b is +
c is +
Last edited on
Topic archived. No new replies allowed.