Thread: Using cin to read a name into 1 string

  1. #1
    Registered User
    Join Date
    Jan 2004
    Posts
    11

    Using cin to read a name into 1 string

    To clarify the title, I want to know how to work past the fact that whitespaces are read as delimiters. So when the name "John Smith" is entered into
    Code:
    string name;
    cin >> name;
    The string will hold "John Smith", not "John."

    Thank you ahead of time.

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    648
    Look up this function in your documentation:
    Code:
    istream &getline(istream &input, string &str, char delim = '\n');

  3. #3
    Registered User
    Join Date
    Dec 2003
    Posts
    101
    Doesn't this work?
    Code:
    string firstName, lastName;
    cin >>firstName >>lastName;
    --

  4. #4
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    ^ yes, but he wants it in one string... to clarify speedy 5's answer, do this:
    Code:
    char name[256];
    cin.getline(name,256,'\n');
    using getline takes the '\n' out of the istream, and using cin.get() leaves the '\n' in the ifstream. I find getline() more handy because I usually don't want the character in there... the middle number can be left out (cin.getline(name,'\n'))... that just makes sure that the system stops reading in after reading that amount of chars without reaching the term char...

    I didn't use the string datatype in my example because I don't know much about it, and I don't think that's the way you do it with strings...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  5. #5
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    You can do it with strings in almost the same way. Here's how:
    Code:
    std::string name;
    std::getline(std::cin, name);
    No need to worry about number of characters read or anything like that. If you are reading from a file, change std::cin to your file stream. If you want something other than a newline as delimiter, add a third argument. And std::getline is found in <string>. Speedy5's answer was fine, but since major_small gave the C style string example I figured I'd give the standard string example.

  6. #6
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Originally posted by major_small
    ^ yes, but he wants it in one string... to clarify speedy 5's answer, do this:
    Code:
    char name[256];
    cin.getline(name,256,'\n');
    using getline takes the '\n' out of the istream, and using cin.get() leaves the '\n' in the ifstream. I find getline() more handy because I usually don't want the character in there... the middle number can be left out (cin.getline(name,'\n'))... that just makes sure that the system stops reading in after reading that amount of chars without reaching the term char...
    Not being an expert in getline() I have this question. If you leave out the len parameter, isn't the function analogous to gets() in C? IOW:
    Code:
    char name[10]
    cin.getline(name,'\n');
    what will happen if you type in 20 or 30 characters? Is C++ smart enough to stop at 10? If not, leaving out the middle number is extremely dangerous.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  7. #7
    Registered User
    Join Date
    Jan 2004
    Posts
    33
    C++ will stop at 10 characters in this instance. You can see this by printing name[10] to the screen after input. I would always use the second paramater however just to be safe.
    “Focused, hard work is the real key to success. Keep your eyes on the goal, and just keep taking the next step towards completing it. " -John Carmack

  8. #8
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Originally posted by /Muad'Dib\
    C++ will stop at 10 characters in this instance. You can see this by printing name[10] to the screen after input. I would always use the second paramater however just to be safe.
    name[10] doesn't exist, what good is printing it? What would you see?

    Test program:
    Code:
    #include <iostream>
    using namespace std;
    int main ()
    {
        char mn[10];
        cin.getline(mn, '\n');
        cout << mn << endl;
        cout << "10=[" << mn[10] << "]" << endl;
        return 0;
    }
    Execution:
    Code:
    d:\>xp
    abcdefghijkl
    abcdefghi
    10=[ ]
    
    d:\>
    Scary. No indication that mn[10] is non-existant. But it did stop reading after 9 characters.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  9. #9
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    I don't think it's exactly dangerous to your machine... it will just try to save it in a place that doesn't exist... it's still an error though... if you try to read past the end of an array either your compiler will tell you it doesn't exist, or your system will have to decide what to do with it... sometimes it'll just put a random character in the stream...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  10. #10
    Its not rocket science vasanth's Avatar
    Join Date
    Jan 2002
    Posts
    1,683
    how about using fgets


    #define SIZE 100
    char array[SIZE];


    fgets(array,SIZE,stdin);


    and it works perfect for me..

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Is C++ smart enough to stop at 10? If not, leaving out the middle number is extremely dangerous.
    In your example, where '\n' has the numeric value of 10, yes. Leaving out the middle argument is dangerous, and it doesn't do what most people would expect. It takes the decimal value of the delimiter charater and uses that as the size argument. So the call:
    Code:
    char name[15];
    cin.getline ( name, '\n' );
    Will read up to int('\n') - 1 characters, or stop when '\n' is reached as that happens to be the default for this overload of getline.
    My best code is written with the delete key.

  12. #12
    Registered User
    Join Date
    Jan 2004
    Posts
    11
    Thanks, everyone. (And sorry about not replying until now )

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Remarkable coincidence.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  14. #14
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Remarkable coincidence.

    You can say that again ... I thought that getline() call looked mighty suspicious.

  15. #15
    Registered User Paz_Rax's Avatar
    Join Date
    Jan 2004
    Posts
    16
    if you want to wait for the user to hit enter to accept the full string you could use the code below with the header conio.h
    Code:
    #include<conio.h>
    #include<iostream.h>
    
    string input(){
         string text = "";
         char get = getch(); 
         while( get != '\r'){     // \r is the enter key
              cout<<get;
              text += get;
              get = getch();
              }
         return text;
    }
    Hope this helped
    "Life, it's all in how you script it."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. getline(function)??
    By dac in forum C++ Programming
    Replies: 7
    Last Post: 03-10-2006, 12:42 PM
  4. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM
  5. Replies: 1
    Last Post: 07-24-2002, 06:33 AM