Thread: help with string/char array (newb)

  1. #16
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    does string variable types not hold spaces
    That should be pretty easy to test yourself:
    Code:
    string str;
    str = "hello world";
    cout<<str<<endl;
    or does the >> what casue it not to be able to have spaces?
    The extraction operator>> is for reading what's called "formatted input", i.e. input that is grouped into words. It is programmed to start reading and skip any leading whitespace(spaces, tabs, newlines) until it finds some input, then it continues reading input until it hits the first trailing whitespace, and then it stops reading. Therefore, the result is it reads in groupings of characters without any of the spaces, tabs, or newlines between words.

    If you want to read in a whole line of data, spaces and all, use getline().

    For char arrays:

    char str[30];
    cin.getline(str, 30);
    //reads 29 chars max or until a newline is reached.
    //Last spot is saved for a '\0' char

    For strings:

    string str;
    cin.getline(str, '\n'); //WRONG

    //SHOULD BE(as per elad's subsequent post):
    string str;
    getline(cin, str);
    Last edited by 7stud; 05-26-2005 at 04:44 PM.

  2. #17
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    I'm pretty sure for STL strings the syntax for getline() is:

    getline(inputStreamName, stringName, terminatingChar);

    where terminating char defaults to newline char.
    You're only born perfect.

  3. #18
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    You are absolutely correct. It looks like I messed up while cutting and pasting.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  3. Replies: 7
    Last Post: 11-25-2008, 01:50 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM