954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Is there an easy way to ignore...

a percent sign? My program asks the user for a percentage rate. It then puts (with cin) the rate into a double. However...if a user tries to type a % after he enters a number...the program goes wack...

rickster11
Light Poster
42 posts since Nov 2007
Reputation Points: 10
Solved Threads: 1
 

If you want the % sine then input the data as a string then convert to double laber so that the % symbol will be removed from the keyboard buffer.

std::string input;
cout << "Enter a percent";
getline(input, cin);
double n;
stringstream str(input);
str >> n;
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Maybe you should take a look at the following code:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string usrInput;
    double dbl = 0;
    cout << "Enter a percent: ";

    getline(cin, usrInput);
    cout << endl;

    if(usrInput.c_str()[usrInput.length()-1] == '%')
    {
        usrInput.replace(usrInput.length()-1, 0, "");

        cout << usrInput << endl;

        dbl = atof(usrInput.c_str());
    } else {
        dbl = atof(usrInput.c_str());
    }

    cout << "The double is: " << dbl << endl;

    return 0;
}


Using Ancient Dragon's method:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main(void)
{
    string str;
    double dbl = 0;

    cout << "Type a number: ";
    cin >> str;
    cout << endl;
    stringstream ss(str);
    ss >> dbl;
    cout << "The number is: " << dbl;

    return 0;
}
tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

Replace..

if(usrInput.c_str()[usrInput.length()-1]=='%')
...

with

if(usrInput[usrInput.length()-1] == '%')
cikara21
Posting Whiz
340 posts since Jul 2008
Reputation Points: 47
Solved Threads: 69
 

Replace..

if(usrInput.c_str()[usrInput.length()-1]=='%')
...

with

if(usrInput[usrInput.length()-1] == '%')
...

Thank you for mentioning that, I didn't know that was possible...

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You