Thread: need help with get() and character array

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    4

    need help with get() and character array

    i've been trying to deal with a very frustrating bug for the better part of the day today, and i have NO CLUE what the hell is going on. this is the seemingly simple code that's killing me

    Code:
    char csaliasname[30];
    .
    .
    .
    .
    .
    cout << "\tWhat would you like the alias of this program to be?" << endl;
          cout << "\t(Any word or phrase up to 30 characters long)" << endl;
    	  cout << "\t";
    
    	  cin.get(csaliasname,30);
    		
          cout << "\t" << csaliasname << " has been added to your Easy Execute\n\tManager" << endl;
          cout << "\t";
    	  system("PAUSE");
    but instead of the expected output, when its supposed to stop and wait for the user to input the desired value for csaliasname, it skips right through it and when it gets to cout << csaliasname << " has been added...etc" it gives a blank space i'd say 8 characters long..before running the vc++ debugger, i initialized csaliasname = "Default", and when the debugger got to call to cin.get(), the 'D' in csaliasname[0] magically disappears! what the hell is going on? i would LOVE an explanation for this. please please someone enlighten me.

    btw i used a cin.get() on another char variable a few lines above all of this and it works fine...i've heard of some surprises arising from cin.get() and cin.getline(), so i thought maybe that was it. i've tried both functions and both have same result

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    76
    Right this is a real pain this one. For some reason when you use get() the first time it leaves the terminating string in the buffer. So when it comes to the second time because the input buffer isn't empty it uses that instead.
    Its easy to fix just before you use cin.get() before the second time call the function cin.ignore(1,'\n') What this does is clear the input buffer so that when you use get the second time it actually sets it to what you want it to be.
    Hope this helps

    Ps. I know this works for the getline function but I think it will work for get as well.

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    4
    great thanks a lot...saved me from even more grief from something so dumb. again i appreciate it

Popular pages Recent additions subscribe to a feed