Read array

  • Thread starter RuthKom
  • Start date
  • #1
2
0

Main Question or Discussion Point

I'm a beginner and currently learning programming by myself. when I read a book I came across an example which I dont 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 dunno why the second "cin>>string1" reads "there"...can anyone tell me the reason behind?
Please help me...Thanks very much:)
 

Answers and Replies

  • #2
jtbell
Mentor
15,585
3,562
The second input operation starts reading where the first one stopped. Or have I missed the point of your question?
 
  • #3
2
0
Thx jtbell
I wanna know why it starts reading where the first one stopped...
 
  • #4
jim mcnamara
Mentor
3,953
2,353
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>
 
  • #5
jtbell
Mentor
15,585
3,562
I wanna 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 lets 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.
 

Related Threads on Read array

  • Last Post
2
Replies
33
Views
2K
Replies
4
Views
10K
Replies
4
Views
8K
Replies
7
Views
4K
Replies
11
Views
31K
Replies
3
Views
2K
Replies
6
Views
3K
Replies
7
Views
7K
Top