Thread: hehe, i ask lotsa questions: making sure no spaces exist

  1. #1
    Registered User
    Join Date
    Nov 2002

    hehe, i ask lotsa questions: making sure no spaces exist

    char[20] pname;
    cin >> pname;
    now, how can i get it to make sure that they havent entered any spaces so the program doesnt crash down? htanx again everyone for answering all my questions!
    In order of learned:
    HTML - Mastered
    CSS - Enough to use
    SSI - Mastered
    PHP - Advanced
    C/C++ - Current Project

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    cin is delimited by white space, so if the user does enter a space then cin will read up to it, but not include it. If you want to read the spaces as well then you need to use getline:

    char pname[20];
    cin.getline ( pname, 20 );

    My best code is written with the delete key.

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Be aware that funny things can happen when you mix calls to istream::operator >>()and istream::getline(). getline extracts the delim char from the stream whereas operator >> leaves the delim in the stream and disregards it next read. So if you do this for instance....
    int a;
    char b[20]
    It will appear that the getline has been skipped but in actual fact all that happened was getline found the delim char left by operator >> and took that as its input. This is easy to fix...
    int a;
    char b[20]
    cin.ignore(80,'\n'); // ignore up to 80 chars or a newline whichever comes first
    cin.getline(b,20); // will now work ok
    Call this a preemptive strike.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :-

  4. #4
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    As Stoned_Coder said...
    The best way is to use ignore(), I had this problem once, and the best way is to use ignore();

  5. #5
    Registered User
    Join Date
    Mar 2002
    cin is a predefined instance of the istream class. As such it has a number of member functions and overloaded operators, two of which are >> and getline()---there are others like get(), ignore(), good(), bad(), fail(), clear(), etc.. A good textbook, or a decent compiler help section can help you learn about them. The most commonly used ones and the problems/quirks associated with them have been described already.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A very long list of questions... maybe to long...
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-16-2007, 05:36 AM
  2. Making Spaces in Output
    By Sentral in forum C++ Programming
    Replies: 3
    Last Post: 06-15-2005, 07:03 PM