473,405 Members | 2,354 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,405 software developers and data experts.

c++ newb inquiry

I've been searching these forums and trying to figure this out on my own but am having problems.

int x;
cin >> x;

if a noninteger value is entered the program goes into an endless loop - is there anything that can be done about this? :confused:

thanks - if you can help elucidate this i would appreciate it as i'm trying to get a firm grasp on c++ and this is throwin off my game
Jun 14 '06 #1
6 2581
so it looks like it loops because of a condition i had set - but if it is passed a noninteger value it just ignores every condition and falls through the code till it returns

any suggestions?
Jun 15 '06 #2
Banfa
9,065 Expert Mod 8TB
Not unless you post the code that is causing the problem
Jun 15 '06 #3
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

/*This program takes two int, one coefficient, and one exponent to calculate the
power of the coefficient - it stores each multiplication in a vector and displays
the progression from 1 through...*/

using namespace std;

//function declaration

int powervec(int coef, int expo, vector<int> &chamber);

int main(int argc, char *argv[])
{
int x = 0, y = 0;

char s; //input character for y/n response
int cnt = 1; //counter for exponential count
int check = 1;//control variable to control loop through process

while(check == 1)//repeat loop while response 'y'
do
{

cnt = 1; //reset counter to 1

cout << "\nEnter two values - One Coefficient & One Exponent\n\n\n";
cout << "Enter Coefficient: ";

while(!(cin >> x))
{cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; break;}
cout << "\nEnter Exponent: ";
while(!(cin >> y))
{cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; break;}
cout << endl;
if(y == 1 && x == 1)
{cout << "\n1 multiplied by 1 is 1\n\n";
cout << "do you want to try again?(y or n):"; cin >> s;
if(s == 'y'){break;}
else {check = 0; break;}
}
vector<int> powvector(y);

powervec(x,y,powvector);

for(vector<int>::iterator iter = powvector.begin(); iter != powvector.end(); iter++, cnt++)
{
cout << x << " to the power of " << cnt << " is: " << *iter << endl;
}

cout << "\nCalculate another power??? (y or n):";

cin >> s;

if(s == 'n'){check = 0;} //escape loop

}while (s == 'y' || s == 'Y');

cout << "\nThank you for calculating powers with my program!!!\n" << endl;

system("PAUSE");
return EXIT_SUCCESS;

}

int powervec(int coef, int expo, vector<int> &chamber)
{
int total = 1;

for(int num = 0; num != expo; num++)
{
total *= coef;
chamber[num] = total;
}

return total;

}

------------------------------------------------------------------------

Again, when ever you enter a noninteger value into x or y, the program loops endlessly.
Jun 15 '06 #4
Banfa
9,065 Expert Mod 8TB
My Comments embedded in the code in bold

Expand|Select|Wrap|Line Numbers
  1. // MethodTest.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include <cstdlib>
  5. #include <iostream>
  6. #include <string>
  7. #include <vector>
  8.  
  9. /*This program takes two int, one coefficient, and one exponent to calculate the
  10. power of the coefficient - it stores each multiplication in a vector and displays
  11. the progression from 1 through...*/
  12.  
  13. using namespace std;
  14.  
  15. //function declaration
  16.  
  17. int powervec(int coef, int expo, vector<int> &chamber);
  18. /* Since this is in the same module as the place it is 
  19.    called from you could prefix this with static */
  20.  
  21. int main(int argc, char *argv[])
  22. {
  23.     int x = 0, y = 0;
  24.  
  25.     char s; //input character for y/n response
  26.     int cnt = 1; //counter for exponential count
  27.     int check = 1;//control variable to control loop through process
  28. /* You seem to be using check as a boolean control variable so why 
  29.    not use the typer bool?  Also check is not very descriptive of what 
  30.    this variable does a name like bContinueRunning might be better */
  31.  
  32.     while(check == 1)//repeat loop while response 'y'
  33. /* This loop is a bit unnecessary, you could just add the 
  34.    condition to the conditions of the do loop like so
  35.  
  36.         }while ((s == 'y' || s == 'Y') && check == 1); 
  37.  
  38.    Although you would also need to change some of your 
  39.    breaks to continues. */
  40.  
  41.         do
  42.         {
  43.  
  44.             cnt = 1; //reset counter to 1
  45.  
  46.             cout << "\nEnter two values - One Coefficient & One Exponent\n\n\n";
  47.             cout << "Enter Coefficient: ";
  48.  
  49.             while(!(cin >> x))
  50.             {cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; break;}
  51. /* This line is part of your problem, you detect the error and output a
  52.    message (cout statement) but instead of re-requesting input you 
  53.    then break out of the loop this code is equivilent to 
  54.  
  55.     if(!(cin >> x))
  56.     {
  57.         cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; 
  58.     }
  59.  
  60.     this means that if the input value is invalid the program just goes ahead and tries to use it.
  61. */
  62.  
  63. /* Your source format is very poor and makes the code less readable, 
  64.    which in turn makes it harder to maintain the 2 normal ways of laying
  65.    out the braces of a loop or if statement would be 
  66.  
  67.     while(!(cin >> x)) {
  68.         cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; 
  69.         break;
  70.     }
  71.  
  72.    or
  73.  
  74.     while(!(cin >> x))
  75.     {
  76.         cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; 
  77.         break;
  78.     }
  79.  
  80.    personally I prefer the second.  Formated like this you might have 
  81.    spotted the break error.
  82. */
  83.             cout << "\nEnter Exponent: ";
  84.             while(!(cin >> y))
  85.             {cout << "\n!!!invalid input received!!!\n\nTry again...\n\n"; break;}
  86. /* Again the same break problem and source code formating.*/
  87.             cout << endl;
  88.             if(y == 1 && x == 1)
  89.             {cout << "\n1 multiplied by 1 is 1\n\n";
  90. /* Source code formating. */
  91.             cout << "do you want to try again?(y or n):"; cin >> s;
  92.             if(s == 'y'){break;}
  93. /* Source code formating and here you only check for y but later 
  94.    on you check for y and Y, you should keep these checks consistent.
  95.    Additionally you are actually repeating the code to ask if the user 
  96.    wants to perform another calculation.  This is bad form as it introduces 
  97.    a maintence issue (if you want to change the method you have to 
  98.    change it in 2 places).  By reorganising the if with an else clause 
  99.    you can have the code that checks for a repeat calculation once at 
  100.    the end of the loop removing this issue. This would also allow you to 
  101.    remove the outer while loop entirely and the variable check. */
  102.             else {check = 0; break;}
  103. /* Source code formating. */
  104.             }
  105.             vector<int> powvector(y);
  106.  
  107.             powervec(x,y,powvector);
  108.  
  109.             for(vector<int>::iterator iter = powvector.begin(); iter != powvector.end(); iter++, cnt++)
  110.             {
  111.                 cout << x << " to the power of " << cnt << " is: " << *iter << endl;
  112.             }
  113.  
  114.             cout << "\nCalculate another power??? (y or n):";
  115.  
  116.             cin >> s;
  117.  
  118.             if(s == 'n'){check = 0;} //escape loop
  119. /* Source code formating and below you check for y and Y, but here 
  120.    you ar checking for n you should keep your checks */
  121.  
  122.         }while (s == 'y' || s == 'Y');
  123.  
  124.         cout << "\nThank you for calculating powers with my program!!!\n" << endl;
  125.  
  126.         system("PAUSE");
  127.         return EXIT_SUCCESS;
  128.  
  129. }
  130.  
  131. int powervec(int coef, int expo, vector<int> &chamber)
  132. /* Since this function clearly does not cope with negative exponents 
  133.    it might be better to have expo as an unsigned or at least 
  134.    check that it is >= 0 */
  135. {
  136.     int total = 1;
  137.  
  138.     for(int num = 0; num != expo; num++)
  139.     {
  140.         total *= coef;
  141.         chamber[num] = total;
  142.     }
  143.  
  144.     return total;
  145.  
  146. }
  147.  
Jun 16 '06 #5
Banfa
9,065 Expert Mod 8TB
After a bit of research I find that rather than

Expand|Select|Wrap|Line Numbers
  1.     int x;
  2.  
  3.     while(!(cin >> x))
  4.     {
  5.         cout << "\n!!!invalid input received!!!\n\nTry again...\n\n";
  6.     }
  7.  
you may find this more reliable

Expand|Select|Wrap|Line Numbers
  1.     char input[100];
  2.     int x;
  3.     char *pEnd;
  4.  
  5.     do
  6.     {
  7.         cin.getline( input, sizeof input );
  8.  
  9.         x = (int)strtol(input, &pEnd, 10);
  10.  
  11.         if (!x)
  12.             cout << "\n!!!invalid input received!!!\n\nTry again...\n\n";
  13.     }
  14.     while(!x);
  15.  
Jun 16 '06 #6
Oi Bantfa!

That rocks...thanks a lot, bro :)

My programming style has totally been impacted in a very positive way

I'm more proficient with selective execution

The way I go about planning is more practical

dude, thank you thank you thank you

just what i needed to here :D
Jun 17 '06 #7

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

Similar topics

11
by: Berislav Lopac | last post by:
Imagine three options: a) There is an XML file. A PHP5 script loads it and puts it into a DOM document object. Then, given an input string, a function looks via XPath for a node with that name...
0
by: claudel | last post by:
Hi I have a newb PHP/Javascript question regarding checkbox processing I'm not sure which area it falls into so I crossposted to comp.lang.php and comp.lang.javascript. I'm trying to...
4
by: Hari | last post by:
Basically I would like to downlod the visual basic 6.0 compiler, but i already have the vb.net compiler. I had to pay for the VB.net IDE, just wondering if I can get the vb 6.0 IDE for free or not....
0
by: David E. | last post by:
So as a programmer, what's the best thing to study? EJB? How much of the J2EE or Enterprise architecture is necessary to no? I guess I need a good overview for a newb like me... thanks.. --...
5
by: Alexandre | last post by:
Hi, Im a newb to dev and python... my first sefl assigned mission was to read a pickled file containing a list with DB like data and convert this to MySQL... So i wrote my first module which...
3
by: Walter | last post by:
But I'm stumped..... I've got a windows 2000 server and I am trying to set up PHPBB on it using a mysql database.. I am very inexperienced on this..... Ive installed mysql V4.0.20d and I can...
3
by: claudel | last post by:
Hi I have a newb PHP/Javascript question regarding checkbox processing I'm not sure which area it falls into so I crossposted to comp.lang.php and comp.lang.javascript. I'm trying to...
1
by: notbob | last post by:
Newb here! Using 4.0.20 on Slack. Slogging through the official manual. At 2.4.3 Securing the Initial MySQL Accounts, I'm finally stopped cold while trying to follow instructions. Here's what I...
4
by: segue | last post by:
Just Curious.
1
by: Anthony J. Biondo Jr. | last post by:
Hi Everyone: I was wondering if it is common practice to use some sort of messaging (MSMQ, WebSphere MQ) with web services. I understand the need for messaging for insert / update transactions,...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.