473,699 Members | 2,720 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cin >> string looping infinitely

8 New Member
Because of a simple cin statement, my program goes into an infinite loop and I'm not sure why. I've used the same code in other programs (only with different variable names and cout statements) and it's worked fine. See code below:

Expand|Select|Wrap|Line Numbers
  1.  
  2. int main () 
  3. {
  4.     BinaryHeap pQueue; // create empty heap
  5.     bool acceptCommand = true;
  6.     string command; // function to perform
  7.  
  8.     while (acceptCommand)
  9.     {    
  10.         // get function to perform
  11.         cout << "Please enter a command: " ;
  12.         cin >> command ;
  13.         cout << endl ;
  14.  
  15.         // act accordingly
  16.         if (command=="createHeap")
  17.         {
  18.             ...
  19.         }
  20.  
  21.         else if (command=="insert")
  22.         {
  23.             ...
  24.         }
  25.  
  26.         else if (command=="deleteMin")
  27.         {
  28.             ...
  29.         }
  30.  
  31.         else if (command=="deleteHeap")
  32.         {
  33.             ...
  34.         }
  35.  
  36.         else if (command=="remove")
  37.         {
  38.             ...
  39.         }
  40.  
  41.         else if (command=="decreaseKey")
  42.         {
  43.             ...
  44.         }
  45.  
  46.         else if (command=="quit")
  47.         {
  48.             acceptCommand = false;            
  49.         }
  50.  
  51.         else // invalid command
  52.         {
  53.             cout << "Command not recognized. Please try again." ;
  54.         }
  55.  
  56.     } // end while
  57.  
  58.     return 0;
  59. }
  60.  
  61.  
Using a BinaryHeap class and associated functions, the above is supposed to take in a command, act accordingly, and then wait to accept the next instruction. When compiled and run on both XCode and TextMate, the input "createHeap 1 2 3 4 5" will execute the createHeap function correctly once but then attempt to re-execute infinitely. It seems I need to reset the cin variable after the command is given, but cin.clear() and cin.ignore() seem to have no effect. Any suggestions? Thanks in advance.
Apr 27 '08 #1
1 2058
weaknessforcats
9,208 Recognized Expert Moderator Expert
You dpn't check that con >> command actaully worked.

If it fails, the input stream goes into a fail state and the operator>> aborts.

Next time around the operator>> sees the fail state and does nothing.

And there you are.

You need to check your >> statements:
Expand|Select|Wrap|Line Numbers
  1. cin >> command;
  2. if (cin.fail())
  3. {
  4.       //Here you need to a) cin.clear() to reset the fail state and
  5.       //b) get rid of the data causing the problem
  6.       //etc...
  7. }
  8.  
Apr 28 '08 #2

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

Similar topics

6
2138
by: Bengt Richter | last post by:
>>> hex(-5) __main__:1: FutureWarning: hex()/oct() of negative int will return a signed string in Python 2.4 and up '0xfffffffb' >>> hex(-5) '0xfffffffb' >>> hex(-5L) '-0x5L' That is sooo ugly. I suppose it is for a backwards compatible repr, but couldn't we
31
14329
by: da Vinci | last post by:
OK, this has got to be a simple one and yet I cannot find the answer in my textbook. How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on? Basically: "Press any key to continue..." I beleive that I am looking for is something along the lines of a....
14
2661
by: LumisROB | last post by:
Is it possible to create matrixes with vector <vector <double >> ? If it is possible which is the element m23 ? You excuse but I am not an expert Thanks ROB
1
2766
by: @ndy | last post by:
Hellow programmers, does anybody has any suggestions for the next problem? I'm looping a recordset and during the loop it allso calculate some things. Now I want display a POPUP FORM with PROGRESSBAR. The maxvalue is the recordsetcount and every loop is value + 1. How can i pass these value to the POPUP form. I've somthing with public tel but it won't work!
17
3033
by: Peter Bromley | last post by:
The following code snippet does not seem to work correcly unsigned __int64 result = 0xFFFFFFFFFFFFFFFF; result = result << 64; Debugger.WriteLine(System::String::Format(S"{0:X16}", __box(result)); result = 0xFFFFFFFFFFFFFFFF; result = result >> 64; Debugger.WriteLine(System::String::Format(S"{0:X16}", __box(result)); __int64 result = -1;
3
2941
by: Olaf Rabbachin | last post by:
Hi *, ich erzeuge zur Laufzeit in einer ASP-Tabelle Tabellenzellen. Im Großteil dieser Zellen befinden sich Checkboxes. Per JS ändere ich beim Click auf eine solche Zelle oder deren Checkbox die Farbe der Zelle. Problem: Bei einem history.back (oder Back-Button am Client) gehen die Client-seitig geänderten Zellfarben verloren. Ich suche nun einen möglichst performanten Weg, diese per StartupScript dort wiederherzustellen. Mein letzter...
11
3711
by: Ole Nielsby | last post by:
First, sorry if this is off-topic, not strictly being a C++ issue. I could not find a ng on numerics or serialization and I figure this ng is the closest I can get. Now the question: I want to serialize doubles in human-readable decimal form and be sure I get the exact same binary values when I read them back. (Right now, I don't care about NaN, infinities etc.)
10
2488
by: Shafik | last post by:
Hello, I am new to C++. I know the reason is probably template instantiation problems ... but what's the *real* reason I cannot declare a: vector<stringv = vector<string>(4); Thanks! --Shafik
12
2442
by: Mark S. | last post by:
Hello, The app in question is lives on a Windows 2003 server with .NET 2.0 running IIS 6. The page of the app in question processes 2000 get requests a second during peak loads. The app uses a Static Object. In this object is a generic List<String>. For every page request this list is looped over only reading not writing each value.
0
8687
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
9174
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...
0
9035
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7751
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
6534
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
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4376
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
3057
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
2347
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.