473,240 Members | 1,671 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,240 software developers and data experts.

infinate loop error with char input

2
Here is a block of code that I am having trouble with. I rewrote it as a main function, so I could isolate the problem to fix it, but still haven't been able to figure out the problem. I am pretty new to C++ still.

As I understood it, when cin is used to get text, it would cut off the text at the first space. That's what I was expecting, but in this code, if you enter two words at once - like "red hat" for example - it will go through the loop cycle and never end, ignoring the cin commands inside the loop. Why are those cin commands ignored when extra text is entered? How can I avoid this?

Thank you all for your help.

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <iostream>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. /**********************************************************************
  7. * This Function lets you choose one or multiple words.
  8. ***********************************************************************/
  9. int main()//inf. loop error if 2 words entered at once
  10. {
  11.     char word[256];
  12.  
  13.     int choice = 3;// I kept getting 2359208 as my variable.
  14.     //I initialized choice to 3 in an attempt to bump it out of the 
  15.     //loop at the switch and force to choose a new word.
  16.  
  17.     //select word
  18.     cout << "Please type a word.\n";
  19.     cin  >> word;
  20.  
  21.     //modify or finish
  22.     do{
  23.        cout << "Is " << word << " correct?\n"
  24.             << "1 - yes\n"
  25.             << "2 - add more\n"
  26.             << "3 - start over\n";
  27.        cin  >> choice;
  28.  
  29.        //only added for debugging.
  30.        cout << "Your choice is " << choice << endl;
  31.  
  32.        switch (choice)
  33.        {
  34.           case 1://word ok, continue. Needed to add case to avoid default case.
  35.              break;
  36.           case 2://add a space and an additional word
  37.           {
  38.              char wordTemp[256];
  39.              cout << "Enter the additional word that you would like to add.\n";
  40.              cin  >> wordTemp;
  41.  
  42.              if ((strlen(word) + strlen(wordTemp)) < 254)
  43.              {
  44.                 strcat (word, " ");
  45.                 strcat (word, wordTemp);
  46.              }
  47.  
  48.              else//word combo too large. Do not combine
  49.                 cout << "Sorry, those words are too long.\n";
  50.  
  51.              break;
  52.           }
  53.           case 3://choose a new word
  54.           {
  55.              cout << "Please re-enter your word.\n";
  56.              cin  >> word;
  57.              break;
  58.           }
  59.           default://invalid input
  60.           {
  61.              cout << "Incorect response. Please select again.\n";
  62.              cin >> choice;
  63.              break;
  64.           }   
  65.        }
  66.     }while (choice != 1);
  67.  
  68.     cout << "You have selected:\n\"" << word << "\"\n";
  69.  
  70.     cout << "press any key and select enter to finish.\n";
  71.     cin >> choice;
  72.  
  73. return 0;
  74. }
  75.  
  76.  
Jan 23 '08 #1
5 2739
gpraghuram
1,275 Expert 1GB
Hi,
The problem is the standard input is having unwanted characters which ur second cin>> is reading due to which you get infinite loop.
So you want to clear the standard input buffer before reading again.
You can use this code to clear the unwanted characters

Expand|Select|Wrap|Line Numbers
  1. do{
  2.     char junk[100]; 
  3.     cin.getline(junk,100); //this will remove unwanted characters
  4.  
  5.        cout << "Is " << word << " correct?\n"
  6.             << "1 - yes\n"
  7.             << "2 - add more\n"
  8.             << "3 - start over\n";
  9.        cin  >> choice;
  10.  
  11.  
Thanks
Raghuram
Jan 23 '08 #2
Poly
2
Thank you so much for the help!
Jan 23 '08 #3
weaknessforcats
9,208 Expert Mod 8TB
do{
char junk[100];
cin.getline(junk,100); //this will remove unwanted characters

cout << "Is " << word << " correct?\n"
<< "1 - yes\n"
<< "2 - add more\n"
<< "3 - start over\n";
cin >> choice;
This removes only 100 characters. Why 100? Why not 50 or 10000??

To flush the input buffer, write function that will get characters individually until EOF is endountered.
Jan 23 '08 #4
gpraghuram
1,275 Expert 1GB
This removes only 100 characters. Why 100? Why not 50 or 10000??

To flush the input buffer, write function that will get characters individually until EOF is endountered.
Whatever i have suggested is only an idea and can be changed by the person who has asked it.
But yours is a good idea to read till EOF


Raghuram
Jan 24 '08 #5
Ganon11
3,652 Expert 2GB
Rather than creating an extra variable to read into, you can just use cin.ignore(100, '\n'); which will discard either 100 characters or all characters until the newline character '\n' is encountered, whichever comes first. This runs into the same problem that weaknessforcats described, however.
Jan 24 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

47
by: Mountain Bikn' Guy | last post by:
Take some standard code such as shown below. It simply loops to add up a series of terms and it produces the correct result. // sum numbers with a loop public int DoSumLooping(int iterations) {...
7
by: JR | last post by:
Hey all, I have read part seven of the FAQ and searched for an answer but can not seem to find one. I am trying to do the all too common verify the data type with CIN. The code from the FAQ...
5
by: titan0111 | last post by:
Hi, it's me again. Thank you guys for helping me with other error messages. This is the source code. It goes throught compiler fine but when I run it, it seems to be in infinite loop.
5
by: Blankdraw | last post by:
I can't get this nested loop to break the outer loop at the 5th data value so control can proceed to the next array col and continue pigeon-holing the next 5 in its own column. Why can I not get...
13
by: Rick | last post by:
The following code will enter an infinate loop when in ReadChars. I can only make it happen when reading a Stream and with this particular XML. If I use the ReadInnerXml call rather than my own...
6
by: iskeletor | last post by:
I didn't finish my program yet but in the input function there is a problem.When i enter E character while loop doesn't end. Why? Can anybody help me where is the error? From now, thanks ;) ...
4
by: Vijaykumar Dave | last post by:
Here is a program of calculator. I have a proble in loop. When key 1-8 is pressed, it works ok but if any character key is pressed, it goes to infinite loop. will any one help me to correct my...
1
by: d0ugg | last post by:
Hi all, I have a little question, my compiler is giving me the following error: error C2784: 'std::basic_ostream<_Elem,_Traits> &std::operator <<(std::basic_ostream<_Elem,_Traits> &,const...
1
by: jerry | last post by:
i have written a simple phonebook program,i'll show you some of the codes,the program's head file is member.h . i suppose the head file works well.so i don't post it. here's the clips of main...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.