473,915 Members | 4,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

infinate loop error with char input

2 New Member
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 2771
gpraghuram
1,275 Recognized Expert Top Contributor
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 New Member
Thank you so much for the help!
Jan 23 '08 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
do{
char junk[100];
cin.getline(jun k,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 Recognized Expert Top Contributor
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 Recognized Expert Specialist
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
12467
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) { int result = 0; for(int i = 1;i <=iterations;i++) { result += i;
7
7303
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 looks like this: #include <iostream>
5
1493
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
2215
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 this nested loop to make sense? This is the last holdup to completion of my silly project. Explaining it from the inside - out, I want to fill a 120-col X 40-row array with data from a file containing 120 data records of 5 2-digit entries per...
13
3288
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 ReadElementBodyAsXml the code works, but is less efficent. ReadElementBodyAsXml is required by my application with .Net Framework 1.1. The code breaks on the second call to ReadElementBodyAsXml with the inner xml: </EGDConfigExtension>...
6
2709
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 ;) #include <stdio.h> #include <stdlib.h> struct MinSpanTree{
4
1909
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 program? Vijaykumar Dave -------------------------------------------------------------------------------------------- #include<stdio.h>
1
1684
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 std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_ostream<_Elem,_Traits> &' from 'std::istream' see declaration of 'std::operator <<' Here is the main part of my project.
1
6033
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 function which i think has problem // this a simple program about phonebook,it can add items,del items,find items and #include "member.h" #include <fstream> #include <vector>
0
10039
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9881
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11354
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
11066
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9732
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8100
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5943
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4778
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.