Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 269
  • Last Modified:

cin problems

BASIS: i'm writing a program with AP classes, which means when i try to input a series of names from the user i have to make a while loop with cin.get(letter), pull in the whole name one character at a time, into the vector(basically an array).
PROBLEM: I found a problem that after prompting the user if they want to enter another name(assuming they type 'y' or yes) the program calls the function that inputs the name again.
only the second time(and every time after) cin doesnt prompt the user and instead ASSIGNS the variable to '\n' which is what i'm using as the escape key for the while loop that is pulling in the letters of the name.  so it escpaes the loop and messes up everything from there. and by the way, i have to use cin.get because names have spaces, and '\n' needs to be the escape key for the loop, for other various reasons.
any help would be GREATLY appreciated!
Thanks!
-T
0
t0astmAn
Asked:
t0astmAn
1 Solution
 
nietodCommented:
Post your code so we can help you with it.
0
 
pagladasuCommented:
I think I can figure your problem with cin. Try something like this. It is a small code snippet which takes care of the enter key.

      char x,ans='y';
      while(ans=='y'){
            cout<<"Name:";
            while((x=cin.get())!='\n'){
                  //do whatever with x - stuff it into array
            }
            //don't forget '\0' at the end of array
            cout<<"Continue:";
            cin.get(ans);
            x=cin.get(); //get rid of another enter key
      }

Hope this will help. Thanks
pagladasu
0
 
paulvzCommented:
You might also try the cin.getline function:

//This array should be the length of the name + 1
//Let's assume it should be 20 characters long.

char name[21];

while (/*repeat condition here*/)
{
  cin.getline(name, 20);
  //Process the data in name
}

The getline function will read 20 characters or until it reaches a delimiter (in this case \n which is default).  Also the delimiter is removed from the stream but not inserted into name.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now