Thread: Simple Gets() problem

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    27

    Simple Gets() problem

    the problem I'm having with the gets function is that it seems to already have some value pre-stored before it runs for the first time. This wouldn't normally be a problem but it messes up ma switch function.

    what I've got is:
    Code:
    char ans;
     
    int main(){
         cout << "Please enter choice: ";
         gets(ans);
    
         switch(ans[0]){
    
              case '1': //case 1 stuff
    
              case '2': //case 2 stuff
    
             default:  cout << "Input not recognised";
                           waitforkeypress();
                           break;
    
    etc
    what happens is basically whenever the program goes to the screen where the switch function is present it displays the default straight away without pressing anything. Then after pressing a key the default message dissappears and the meu part comes up again.

    This happens every time the screen is first displayed, whether just compiled and ran or returned to. If I use cin >> the problem is gone, but this happens in other sections of my code where whitespace characters may be present so the gets function is needed. Can someone tell me why this is?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Never use gets. Visit the FAQ.

    (But it "works" with a string -- not a single character.)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    NEVER USE GETS!!! See my sig as to why, also gets is a C
    function, this is C++ board - the fgets equivalent is cin.getline()
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    27
    I've read the bit on fgets() in the faq, but I find it a little confusing as I don't understand pointers. I only started teaching myself this language 3 weeks ago so I'm struggling with functions like fgets or cin.getline() when the book I bought only talks about gets

  5. #5
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    Get a new book then. fgets works with C-style strings:

    char a_string [20];
    .
    .
    .
    fgets (a_string, 20, stdin);

    works fine like that.

    The only thing is that fgets can leave an unwanted newline in
    your string. The fgets link in my sig shows how to remove it.
    getline works in the same manner, but I think it can take C++
    strings - not sure of how to use it myself since I haven't had to
    read in a string in ages.
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  6. #6
    Registered User
    Join Date
    May 2006
    Posts
    27
    just noticed that one of ma switch bits uses integers for the variable so am I right in saying fgets() can't be used seeing as you define the size of the string in it?

    I know this doesn't matter as cin >> works fine, but its annoying if you hit a space and it loops the default bit for each whitespace character.

    I'll try it on the parts where there are spaces and get back to you

    P.S. I do indeed need to get a new book, the one I've got just now is pretty bad. The easy bits are in nice detail but the more tricky parts are just glanced over. It has one paragraph on getline with no example and a page on cin.get, half of which is an example.

  7. #7
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Why bother with any of that at all?
    Code:
        int ans = 0;
        cout << "Enter choice: ";
        while(!(cin >> ans)) {
        // If we fail to get a real digit, we'll know, and recover
        // by cleaning the buffer for cin.
           cin.clear();
           cin.ignore(numeric_limits<streamsize>::max(), '\n');
           cout << "Enter choice: ";
        }
        switch(ans) {
            case 1:
                 // ...
                 break;
            case 2: 
                 // ...
                 break;
           // ...
           default: 
                cout << "Bad choice!" ;
        }
    Last edited by whiteflags; 05-24-2006 at 06:59 PM.

  8. #8
    Registered User
    Join Date
    May 2006
    Posts
    27
    There's two things with that though

    I don't fully understand the numeric_limits<streamsize>::max() bit, are they variables or library functions?

    Also, seeing as its still using cin, i'm assuming it still can't handle whitespace characters

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    >>I don't fully understand the numeric_limits<streamsize>::max() bit, are they variables or library functions?
    numeric_limits holds lots of properties for built in types. streamsize is one of those types, and max() just returns the largest amount of data it can hold. You need to include <limits> to use it.

    >>Also, seeing as its still using cin, i'm assuming it still can't handle whitespace characters
    what are you talking about? Yes it does, the insertion operator reads everything the user types and tries to shove it in another variable.
    Last edited by whiteflags; 05-24-2006 at 07:18 PM.

  10. #10
    Registered User
    Join Date
    May 2006
    Posts
    27
    I get you on the variables.

    fgets still doesn't work, it still messes up my switch function by performing the default before the user inputs anything and citizen's bit won't work in some parts of my code as the input variable is a char and whitespace characters may be present that need to be read.

    also, when I use fgets on other bits where it reads a user's input and save it to a list in an array, the fgets and gets doesn't wait for any input and saves nothing to the array (a new line in the case of fgets). Any reason why this is? I don't get it.

  11. #11
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    FAQ > How do I... (Level 1) > Obtain a string from the user (C++)
    FAQ > How do I... (Level 1) > Convert a string to a int (C++)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  12. #12
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    If you really need whitespace characters, get them somewhere else. It's incredibly stupid (read: unreliable) to ask for a number and expect the user to type like eight spaces.

    Not to mention it will be a waste of time to read the entire string, track down one number, convert it to a character or integer, and then use it in a switch.

  13. #13
    Registered User
    Join Date
    May 2006
    Posts
    27
    well its not really stupid if you actually read all of my post prior to daves. I said in other parts I use it to save the input to an array. No mention of a number there or even a switch function, nor did I mention i wanted the user to type in a string of any length so I could track down one number.

    The data saved could be a sentence or maybe just a single word, hence why I said it was defined as a char not as an int and the need to it to detect whitespace characters.

    So preferably read the entire post and offer something constructive rather than calling some newcomers programming methods stupid. I'm new to this language so of course I know my methods are not the best or most practical. The last thing i need is someone reminding me that when I am asking for help

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    I may come off as mean, but I'm simply telling you that I think it won't work reasonably well. Part of my problem is your prompting. If a user reads "Enter a choice:" they enter their choice and press enter, not thinking about whitespace as it is usually meaningless. If you had said, "Enter a choice and some whitespace", that's different.

    That being said, the insertion operator works with all built in types by default, and even char arrays to some extent. Flagrantly dismissing my working, tried and tested solution as bad without even trying it was not going to impress me either.

    That also being said, read the things Dave posted. You can get a string safely the C++ way, and convert the number part for your switch statement, and the string will still be there later. I am not a fan of mixing C with C++.

  15. #15
    Registered User
    Join Date
    May 2006
    Posts
    27
    I never said I didn't try your bit of code, I just said it wouldn't work for some parts. The enter choice is just there to illustrate things and is not the actual prompting, there are other things displayed at the same time as well. It was just to save space and time, I've got sections where it says enter stock number, enter description, select option to proceed, etc.

    basically, for things like description, if I use gets, fgets, cin.get, cin.getline to detect the user's input, all that happens is "Enter Description:" flashes up and then it moves onto the next screen, not waiting for any input.

    If I changed it to cin >>, it waited for a user input before proceeding, which is where my problem starts as sentences may be used.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A simple file I/O problem
    By eecoder in forum C Programming
    Replies: 10
    Last Post: 10-16-2010, 11:00 PM
  2. Problem in simple code.
    By richdb in forum C Programming
    Replies: 6
    Last Post: 03-20-2006, 02:45 AM
  3. Problem in very simple code
    By richdb in forum C Programming
    Replies: 22
    Last Post: 01-14-2006, 09:10 PM
  4. Simple Initialization Problem
    By PsyK in forum C++ Programming
    Replies: 7
    Last Post: 04-30-2004, 07:37 PM
  5. Simple OO Problem
    By bstempi in forum C++ Programming
    Replies: 1
    Last Post: 04-30-2004, 05:33 PM