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

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    41

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

    Code:
    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
    Posts
    9,897
    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 );

    -Prelude
    My best code is written with the delete key.

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    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....
    Code:
    int a;
    char b[20]
    cin>>a;
    cin.getline(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...
    Code:
    int a;
    char b[20]
    cin>>a;
    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 :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

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

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    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