Jump to content

isdigit

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
I only want a user to input numbers - does C++ have some sort of try-catch? I came across isdigit(), but I believe that is to check whether a character is a number. I came up with this that works excellent to check if a string contains all numbers

[highlight="cpp"]int main () {
bool isString = false;
string x;

cout << "Enter a number: ";

cin >> x;
for(int i = 0; i < x.length(); i++) {
if (!isdigit(x[i])) {
isString = true;
}
}

return 0;

}[/highlight]

But once its done, its still a string and I cant use it to perform math operations on. Can I cast it to an integer? Is there a better way to accomplish this?

#2
upredsun

upredsun

    Newbie

  • Members
  • Pip
  • 9 posts
you can use sprintf function to cast string to an integer.
http://www.upredsun.com
**Easily and automatically build tcp-based or udp-based network protocol source code**

#3
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
I would rather use std::stringstream, now when we're playing around with std::strings anyway.
template <typename Type>
Type Convert(std::string String)
{
        Type Variable;
        std::stringstream SS(String);
        SS >> Variable;
        return Variable;
}
This takes a string and spits it out into whatever type you're specifying. To spit it out as an integer, then you shall do like this:
std::string String = "1234";
int Number = Convert<int>(String);


#4
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
C++ has try catch yes but it isn't used all that much (people prefer C style return values).

[HIGHLIGHT="C++"]
try {
throw 1;
} catch (int i) {
cout << i << "\n";
}[/HIGHLIGHT]

You can throw just about any type. Java exceptions are generally just glorified strings, you could just throw a string in C++.

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
[HIGHLIGHT="C++"]
#include <math.h>
using namespace System;

//this function can handle unsigned numbers in any radix from 1 to 26.
unsigned __int32 StrToNum(char *Str,unsigned int base)
{
char *BaseStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned __int32 Num = 0,currpow,strsz = 0;
//get string size
while(Str[strsz] != '\0')
++strsz;
for(currpow = strsz - 1; currpow >= 0; --currpow)
{
if(InStr(BaseStr,Str[strsz - currpow - 1]) != -1)
Num += (unsigned __int32)(InStr(BaseStr,Str[strsz - currpow - 1]) * pow((double)base,(int)currpow));
else
throw gcnew System::ArgumentException("Not a number!");
}
return Num;
}

signed __int32 InStr(char *Str,char SearchChar)
{
signed __int32 i = 0;
while(Str[i] != '\0')
{
if(Str[i] == SearchChar)
return i;
else
++i;
}
return -1;
}
[/HIGHLIGHT]