Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Read array

  1. Apr 10, 2008 #1
    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 (Text):
    #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:)
  2. jcsd
  3. Apr 10, 2008 #2


    User Avatar

    Staff: Mentor

    The second input operation starts reading where the first one stopped. Or have I missed the point of your question?
  4. Apr 10, 2008 #3
    Thx jtbell
    I wanna know why it starts reading where the first one stopped...
  5. Apr 10, 2008 #4

    jim mcnamara

    User Avatar
    Science Advisor
    Gold Member

    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>
  6. Apr 10, 2008 #5


    User Avatar

    Staff: Mentor

    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.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?