Understanding C++ Program Inputs: A Beginner's Guide

  • Context: C/C++ 
  • Thread starter Thread starter RuthKom
  • Start date Start date
  • Tags Tags
    C++ Program
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
RuthKom
Messages
2
Reaction score
0
I'm a beginner and currently learning programming by myself. when I read a book I came across an example which I don't quite understand.
Code:
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
   char string1[ 20 ];                // reserves 20 characters
   char string2[] = "string literal"; // reserves 15 characters

   // read string from user into array string2
   cout << "Enter the string \"hello there\": ";
  [B] cin >> string1;                   // reads "hello" [/B]
   cout<< "\nstring1 is: " <<string1<<endl;

   [B]cin >> string1;  // reads "there"[/B]
   cout << "\nstring1 is: " << string1 << endl;

   return 0;  
}

I know that space terminates the input when the first "cin>>string1" statement is executed, but I don't know why the second "cin>>string1" reads "there"...can anyone tell me the reason behind?
Please help me...Thanks very much:)
 
Physics news on Phys.org
Thx jtbell
I want to know why it starts reading where the first one stopped...
 
cin operates on the basis of a console or terminal. The terminal driver "sends" blocks of text to the OS -> program when it gets a carraige return - newline - ie., you hit <return>
 
RuthKom said:
I want to know why it starts reading where the first one stopped...

Because that's the way the language was designed!

I think it's useful, because it let's you read part of a line, examine what you've read, and then read the rest of the line differently depending on what the first part of the line contains.