开发者

In C++ How can I tell the difference between integers and characters?

I am currently learning C++ and I have been asked to make a program which will calculate the interest that would be paid on a deposit of a given size. One of the requirements is that we display an error message when non-integer data is entered.

I however cannot work ou开发者_如何转开发t how to detect if non-integer data has been entered. If anyone could provide an example of how this problem is solved it would be much appreciated!


You don't have to check yourself. The expression (std::cin >> YourInteger) evaluates to a bool, whcih is true if and only if YourInteger was succesfully read. This leads to the idiom

int YourInteger;
if (std::cin >> YourInteger) {
  std::cout << YourInteger << std::endl;
} else {
  std::cout << "Not an integer\n";
}


this should be a clear enough starting point.

char* GetInt(char* str, int& n)
{
    n = 0;
    // skip over all non-digit characters
    while(*str && !isdigit(*str) )
        ++str;
    // convert all digits to an integer
    while( *str && isdigit(*str) )
    {
        n = (n * 10) + *str - '0';
        ++str;
    }
    return str;
}


You need to find out if the input value contains non numeric characters. That is, anything other than 0-9.

You have to first take input as string and then verify if every digit is indeed numeric.

You can iterate the string and test if each character is a valid digit using the built in function isdigit() defined in <cctype>. You might also want to allow for a single comma if you're working with decimal numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜