# Any C++ programmers out there? I need a little help.

**URL:** <https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420>\
**Category:** Factual Questions\
**Created:** [October 24, 2003, 11:51pm UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420 "2003-10-24T23:51:01Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![HPL](https://avatars.discourse-cdn.com/v4/letter/h/3da27b/32.png) [@HPL](https://boards.straightdope.com/u/HPL)\
**Post date:** [October 24, 2003, 11:51pm UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/1 "2003-10-24T23:51:01Z")

</div>

I’m doing a project for my C++ college class and while it’s very close to working, I am running into an annoying glitch.

As part of the guidelines, the program will take user entered data from a prompt and process via a series of loops and if else statements. It is also supposed to discard bad data(in this case negative numbers) and then bring back the prompt for the user to re-input his answer and to keep doing so until he does it correctly. I’ve succesfully done that but now have a new problem.

When I test it and type in a non-numerical character(say, a letter or a symbol), the program goes into an ifinite loop and I have to control-C out of it.

I know I have to tell the program to loop properly and go back to the input prompt (“Enter number here”) if a non-numerical character is entered. At the moment though, I’m somewhat at a loss as to how to accomplish this in a fairly simple way. I’ve been going through the textbook but nothing is jumping out at me.

Any suggestions?

---

<div class="post-metadata">

**Author:** ![Achernar](https://avatars.discourse-cdn.com/v4/letter/a/e274bd/32.png) [@Achernar](https://boards.straightdope.com/u/Achernar)\
**Post date:** [October 24, 2003, 11:57pm UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/2 "2003-10-24T23:57:07Z")

</div>

You could post your code.

---

<div class="post-metadata">

**Author:** ![HPL](https://avatars.discourse-cdn.com/v4/letter/h/3da27b/32.png) [@HPL](https://boards.straightdope.com/u/HPL)\
**Post date:** [October 25, 2003, 12:17am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/3 "2003-10-25T00:17:42Z")

</div>

//loads proper data library for interface.  
#include \<iostream.h\>  
//loads proper data library for manipulators  
#include \<iomanip\>

int main()  
{

```
    //Declare variables
    float loan = 0; //The amount of the loan
    float intrate = 0; //The Interest rate. 
    float apint = 0; //The applied interest  
    float monpay = 0; //The monthly payment
    float mdmonpay = 0; //The monthly payment
    int month = 0; //the months counter

   //Print a message telling the user what this program does
    cout &lt;&lt; "Welcome to Student Loan scheduler. ";
    cout &lt;&lt; "This program will find the amount of time";
    cout &lt;&lt; " it will take you to pay off your loan.";
    cout &lt;&lt; "Let's go!" &lt;&lt;endl;
    cout &lt;&lt; endl;

    //Set trailing zeros
    cout.setf(ios::fixed, ios::floatfield);
    cout.precision(2);
    cout.setf(ios::showpoint);

   //while loop takes data and checks for errors
    while(loan &lt;= 0)
    {

    //Prompt the user to enter the loan amount
    cout &lt;&lt; "Please enter the loan amount:$";
    cin&gt;&gt;loan;
    cout &lt;&lt; endl;

    //Echo loan
    cout &lt;&lt; "You have entered: $" &lt;&lt;loan &lt;&lt; endl;

//Display error message if loan is a negative //amount, loops back for input of amount if not
    if(loan &lt;= 0)
            {
            cout&lt;&lt;"You have entered a negative amount.";
            cout&lt;&lt;"Please enter a postive amount"&lt;&lt;endl;
            }
    }

```

This is not the entirely of it, but all that I felt could possibly be relevent to my question.

---

<div class="post-metadata">

**Author:** ![collinsc](https://avatars.discourse-cdn.com/v4/letter/c/f6c823/32.png) [@collinsc](https://boards.straightdope.com/u/collinsc)\
**Post date:** [October 25, 2003, 12:19am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/4 "2003-10-25T00:19:30Z")

</div>

Yeah, youre likely trying to do some math on a capital R. Or something to that effect.

If you want you can use the isdigit() function in \<ctype\>

and do something like:

do{

prompt;  
get data into var;  
etc…;  
}while (!isdigit(var))

---

<div class="post-metadata">

**Author:** ![Cornelius\_Tuggerson](https://avatars.discourse-cdn.com/v4/letter/c/13edae/32.png) [@Cornelius\_Tuggerson](https://boards.straightdope.com/u/Cornelius_Tuggerson)\
**Post date:** [October 25, 2003, 12:28am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/5 "2003-10-25T00:28:12Z")

</div>

The reason you get this error is because you are declaring an indeger and trying to put a character into it. like:  
int a;  
cin\>\>a;  
and then the user enters ‘b’ or something instead of a number. To avoid this problem declare a character and then use it as an integer later. Like:  
char x;  
int y;  
cin\>\>x;  
if() //Put your logic to check for validity here  
y=atoi(x); //This will turn a character into an integer if it is valid

As you can see it all boils down to getting the input in from a user as a character and then using it as an integer. The best site for these type of questions is [www.experts-exchange.com](http://www.experts-exchange.com) Enjoy

---

<div class="post-metadata">

**Author:** ![Mbossa](https://avatars.discourse-cdn.com/v4/letter/m/73ab20/32.png) [@Mbossa](https://boards.straightdope.com/u/Mbossa)\
**Post date:** [October 25, 2003, 12:29am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/6 "2003-10-25T00:29:50Z")

</div>

Check out [http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.3](http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.3). This seems to be pretty close to exactly what you are asking.

---

<div class="post-metadata">

**Author:** ![ultrafilter](https://avatars.discourse-cdn.com/v4/letter/u/3d9bf3/32.png) [@ultrafilter](https://boards.straightdope.com/u/ultrafilter)\
**Post date:** [October 25, 2003, 2:45am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/7 "2003-10-25T02:45:35Z")

</div>

The ascii values for integers are 48-57. If the users input falls in that range (including the endpoints), it’s an integer. Otherwise, it ain’t.

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 5:03am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/8 "2003-10-25T05:03:38Z")

</div>

> [@](#):
>
> \*Originally posted by HPL \*  
> //loads proper data library for interface.  
> #include \<iostream.h\>  
> //loads proper data library for manipulators  
> #include \<iomanip\>
> 
> int main()  
> {
> 
> ```
> //Declare variables
> float loan = 0; //The amount of the loan
> float intrate = 0; //The Interest rate. 
> float apint = 0; //The applied interest  
> float monpay = 0; //The monthly payment
> float mdmonpay = 0; //The monthly payment
> int month = 0; //the months counter
> 
> //Print a message telling the user what this program does
> cout &lt;&lt; "Welcome to Student Loan scheduler. ";
> cout &lt;&lt; "This program will find the amount of time";
> cout &lt;&lt; " it will take you to pay off your loan.";
> cout &lt;&lt; "Let's go!" &lt;&lt;endl;
> cout &lt;&lt; endl;
> 
> //Set trailing zeros
> cout.setf(ios::fixed, ios::floatfield);
> cout.precision(2);
> cout.setf(ios::showpoint);
> 
> //while loop takes data and checks for errors
> ** 
>     
> //Prompt the user to enter the loan amount
> cout &lt;&lt; "Please enter the loan amount:$";
> cin&gt;&gt;loan;
> cout &lt;&lt; endl;
> 
> //Echo loan
> if (loan is between the range that ultrafilter gave)
> {
> // put code in here for valid characters
> // call function to perform math
> 
> cout &lt;&lt; "You have entered: $" &lt;&lt;loan &lt;&lt; endl;
> }
> 
> //Display error message if loan is a negative //amount, loops back for input of amount if not
> else
> {
> while (boolean_value==true)
> {     
> cout&lt;&lt;"You have entered a negative amount.";
> cout&lt;&lt;"Please enter a postive amount"&lt;&lt;endl;
> cin&gt;&gt;loan;
> 
> if (loan is between range that ultrafilter gave)
> {
> //what you will do if they enter a right value--function call
> boolean_value=false;
> }// end if
> } //end while
> 
> ```
> 
> }//else
> 
> ```
> }
> 
> ```
> 
> \*\*  
> This is not the entirely of it, but all that I felt could possibly be relevent to my question.

I tried rearranging this code so that it would work.

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 5:11am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/9 "2003-10-25T05:11:00Z")

</div>

Does C++ have any isVar function or a isNumerical functions like VB, or at least vbscript?  
[cpluscplus.com](http://www.cplusplus.com)

---

<div class="post-metadata">

**Author:** ![collinsc](https://avatars.discourse-cdn.com/v4/letter/c/f6c823/32.png) [@collinsc](https://boards.straightdope.com/u/collinsc)\
**Post date:** [October 25, 2003, 5:35am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/10 "2003-10-25T05:35:30Z")

</div>

> [@](#):
>
> \*Originally posted by Computer Guru \*  
> \*\*Does C++ have any isVar function or a isNumerical functions like VB, or at least vbscript? \*\*

Yes, many. Like I posted above, the ctype include has a slew of them.

isalpha  
isalnum  
isdigit  
isspace  
isprint  
ispuntc  
etc

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 5:37am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/11 "2003-10-25T05:37:30Z")

</div>

Thanks.

So, HPL, put if ((loan \>=0) && (!isalpha(loan)))  
{  
//and so on.

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 5:43am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/12 "2003-10-25T05:43:49Z")

</div>

> [@](#):
>
> \*Originally posted by HPL \*  
> \*\*//loads proper data library for interface.  
> #include \<iostream.h\>  
> //loads proper data library for manipulators  
> #include \<iomanip\>
> 
> int main()  
> {
> 
> ```
> //Declare variables
> float loan = 0; //The amount of the loan
> float intrate = 0; //The Interest rate. 
> float apint = 0; //The applied interest  
> float monpay = 0; //The monthly payment
> float mdmonpay = 0; //The monthly payment
> int month = 0; //the months counter
> 
> //Print a message telling the user what this program does
> cout &lt;&lt; "Welcome to Student Loan scheduler. ";
> cout &lt;&lt; "This program will find the amount of time";
> cout &lt;&lt; " it will take you to pay off your loan.";
> cout &lt;&lt; "Let's go!" &lt;&lt;endl;
> cout &lt;&lt; endl;
> 
> //Set trailing zeros
> cout.setf(ios::fixed, ios::floatfield);
> cout.precision(2);
> cout.setf(ios::showpoint);
> 
> //while loop takes data and checks for errors
> while(loan &lt;= 0)
> {
> 
> //Prompt the user to enter the loan amount
> cout &lt;&lt; "Please enter the loan amount:$";
> cin&gt;&gt;loan;
> cout &lt;&lt; endl;
> 
> //Echo loan
> cout &lt;&lt; "You have entered: $" &lt;&lt;loan &lt;&lt; endl;
> 
> //Display error message if loan is a negative //amount, loops back for input of amount if not
> if(loan &lt;= 0)
> {
> cout&lt;&lt;"You have entered a negative amount.";
> cout&lt;&lt;"Please enter a postive amount"&lt;&lt;endl;
> }
> }
> 
> ```
> 
> This is not the entirely of it, but all that I felt could possibly be relevent to my question. \*\*

I have a question for you. Why are you starting out the loop before you ask for the loan? I think it’s better practice asking the loan before the loop and ask again at the end of the loop. Any other programmers out there: Is this better?

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 5:48am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/13 "2003-10-25T05:48:55Z")

</div>

> [@](#):
>
> \*Originally posted by HPL \*  
> \*\*I’m doing a project for my C++ college class and while it’s very close to working, I am running into an annoying glitch.
> 
> As part of the guidelines, the program will take user entered data from a prompt and process via a series of loops and if else statements. It is also supposed to discard bad data(in this case negative numbers) and then bring back the prompt for the user to re-input his answer and to keep doing so until he does it correctly. I’ve succesfully done that but now have a new problem.
> 
> When I test it and type in a non-numerical character(say, a letter or a symbol), the program goes into an ifinite loop and I have to control-C out of it.
> 
> I know I have to tell the program to loop properly and go back to the input prompt (“Enter number here”) if a non-numerical character is entered. At the moment though, I’m somewhat at a loss as to how to accomplish this in a fairly simple way. I’ve been going through the textbook but nothing is jumping out at me.
> 
> Any suggestions? \*\*

This is just a suggestion. Do it your way. I was just giving an example of how I would have done it. Everyone has different programming styles.

---

<div class="post-metadata">

**Author:** ![HPL](https://avatars.discourse-cdn.com/v4/letter/h/3da27b/32.png) [@HPL](https://boards.straightdope.com/u/HPL)\
**Post date:** [October 25, 2003, 6:00am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/14 "2003-10-25T06:00:57Z")

</div>

> [@](#):
>
> \*Originally posted by Computer Guru \*  
> \*\*I have a question for you. Why are you starting out the loop before you ask for the loan? I think it’s better practice asking the loan before the loop and ask again at the end of the loop. Any other programmers out there: Is this better? \*\*

Well, I had it outside the loop before, but I want it to automatically re-prompt for the data if the data is not valid(which at this point is a negative number).

I’m trying to keep it realitivly simple, because I’m still rather new to loops.

---

<div class="post-metadata">

**Author:** ![LtningBug](https://avatars.discourse-cdn.com/v4/letter/l/73ab20/32.png) [@LtningBug](https://boards.straightdope.com/u/LtningBug)\
**Post date:** [October 25, 2003, 6:42am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/15 "2003-10-25T06:42:27Z")

</div>

After a bit of coding with g++, I figured out what the problem is with the OP’s original code. There is no problem with order or anything like that (well, except for a missing ‘}’ at the end). The problem is the istream object cin is put into a bad state after the cin \>\> loan call. To continue with life, you need to clear the bad state and flush what’s in the buffer:

```auto

// Is the console in in a bad state?
if (!cin)
{
    // Clear the bad state.
    cin.clear();
    // Flush the buffer.
    while('
' != cin.peek())
        cin.get();
}

```

This works with the Gnu g++ compiler, and should work with the VC++ compiler.

---

<div class="post-metadata">

**Author:** ![LtningBug](https://avatars.discourse-cdn.com/v4/letter/l/73ab20/32.png) [@LtningBug](https://boards.straightdope.com/u/LtningBug)\
**Post date:** [October 25, 2003, 7:00am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/16 "2003-10-25T07:00:35Z")

</div>

Follow up: that bit of code goes in the “if (loan \<= 0)” block.

Also, another way to do this properly (with a shout out to all the old school C homies):

```auto

// Some sample code
// iostream for the cin and cout
#include <iostream>
// stdio for sscanf
#include <stdio.h>

int main()
{
    float ftNumber;
    char szInputBuffer[1024];
    
    do
    {
        cout << "Enter a happy float: ";
        cin.getline(szInputBuffer, sizeof(szInputBuffer));

        // Set ftNumber to 0, because sscanf won't change ftNumber
        // if a float isn't available.
        ftNumber = 0;

        // sscanf: String Scan Function. Parses first argument
        // (a char string) using specifiers in second argument.
        // For any variable other than a string, the following 
        // arguments must be pointers (i.e. &ftNumber instead of
        // ftNumber) (strings are actually already pointers).
        sscanf(szInputBuffer, "%f", &ftNumber);

        if (0 == ftNumber)
        {
            cout << "0 is not a happy float :-(" << endl;
            cout << "Try again!" << endl;
        }
    } while (0 == ftNumber);
    cout << "Now, " << ftNumber << " is a happy float :-)" << endl;
    return 0;
}

```

---

<div class="post-metadata">

**Author:** ![LtningBug](https://avatars.discourse-cdn.com/v4/letter/l/73ab20/32.png) [@LtningBug](https://boards.straightdope.com/u/LtningBug)\
**Post date:** [October 25, 2003, 7:27am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/17 "2003-10-25T07:27:17Z")

</div>

> [@](#):
>
> \*Originally posted by Computer Guru \*  
> \*\*Thanks.
> 
> So, HPL, put if ((loan \>=0) && (!isalpha(loan)))  
> {  
> //and so on. \*\*

This will not work. isalpha takes a character (‘a’, ‘%’, ‘1’) and checks to see if it’s a letter (such as ‘a’ or ‘Z’, instead of ‘2’ or ‘;’). loan is a float, not a character.

> [@](#):
>
> \*Originally posted by Computer Guru \*  
> **I have a question for you. Why are you starting out the loop before you ask for the loan? I think it’s better practice asking the loan before the loop and ask again at the end of the loop. Any other programmers out there: Is this better?**

As long as _loan_ is initialized to 0.0 before entering the while loop, this is perfectly fine. However, using a do {} while loop would be a more natural solution. Having more than one copy of the input gathering code raises the hairs on the back of my neck (if at all possible, I never have two copies of the same code that do the same thing: twice as much code = twice as many chances for a bug, and if you find a bug in one copy you need to remember to fix it in the other copy).

The way to choose between the while{} and do{}while loops is to ask yourself: will this code run at least once? If the code in the loop needs to run at least once before the condition matters, the do{}while loop is what you want.

Another thing that helps with loops, **HPL** , is proper indentation. I can’t tell if you had indentation that was lost when you posted your code, but if you aren’t using indentation, you should start. (Any time you’re in a loop, indent should increase.)

p.s. sscanf can cause some hairy problems if you don’t know how to use it, so when in doubt just use the method I outlined in my first post with the cin object.

And kudos to **Mbossa** for posting a link to a site that answers the question succinctly.

---

<div class="post-metadata">

**Author:** ![Ms2001](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/ms2001/32/18463_2.png) [@Ms2001](https://boards.straightdope.com/u/Ms2001)\
**Post date:** [October 25, 2003, 9:34am UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/18 "2003-10-25T09:34:09Z")

</div>

> [@](#):
>
> \*Originally posted by faldureon \*  
> **if() //Put your logic to check for validity here  
> y=atoi(x); //This will turn a character into an integer if it is valid**

atoi is for strings, not characters. To convert a character to an integer, use:

if (isdigit(x)) y = x - ‘0’;

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 2:10pm UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/19 "2003-10-25T14:10:36Z")

</div>

> [@](#):
>
> \*Originally posted by HPL \*  
> \*\*Well, I had it outside the loop before, but I want it to automatically re-prompt for the data if the data is not valid(which at this point is a negative number).
> 
> I’m trying to keep it realitivly simple, because I’m still rather new to loops. \*\*

I thought about what I said earlier. The way you have it is ok. The order that is.

---

<div class="post-metadata">

**Author:** ![Computer\_Guru](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Computer\_Guru](https://boards.straightdope.com/u/Computer_Guru)\
**Post date:** [October 25, 2003, 2:19pm UTC](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420/20 "2003-10-25T14:19:34Z")

</div>

> [@](#):
>
> \*Originally posted by LtningBug \*  
> \*\*This will not work. isalpha takes a character (‘a’, ‘%’, ‘1’) and checks to see if it’s a letter (such as ‘a’ or ‘Z’, instead of ‘2’ or ‘;’). loan is a float, not a character.
> 
> \*\*

What does that function return if it’s a letter? I put ! to make it if it isn’t a letter.

> [@](#):
>
> \*\*  
> As long as _loan_ is initialized to 0.0 before entering the while loop, this is perfectly fine. However, using a do {} while loop would be a more natural solution. Having more than one copy of the input gathering code raises the hairs on the back of my neck (if at all possible, I never have two copies of the same code that do the same thing: twice as much code = twice as many chances for a bug, and if you find a bug in one copy you need to remember to fix it in the other copy).
> 
> \*\*

I was thinking of something different when I asked that question. In my modifications I made to it, I had a conditional before the loop, and then put this while loop in an else statement. But to come to think about it, you are right about trying not to repeat the code like I did. Less chance for bugs. Of course, that’s why I like function calls and Objects.

> [@](#):
>
> \*\*  
> The way to choose between the while{} and do{}while loops is to ask yourself: will this code run at least once? If the code in the loop needs to run at least once before the condition matters, the do{}while loop is what you want.
> 
> Another thing that helps with loops, **HPL** , is proper indentation. I can’t tell if you had indentation that was lost when you posted your code, but if you aren’t using indentation, you should start. (Any time you’re in a loop, indent should increase.)  
> \*\*

ANother thing that I found usefull is putting comments at the end of each brace signalling the end of what bracket of code it closes. See my post above where I changed your code. You don’t need to change anything about your order.

[Next page](https://boards.straightdope.com/t/any-c-programmers-out-there-i-need-a-little-help/209420.md?page=2)
