You are here:

C++/checking if a string consists of all numbers or not.

Advertisement


Question
Hi, i was wondering if there was a way to check if a string consists of all numbers or not.

i know that it first transfers all numbers into it's char-code # and then goes through a for loop
and checks if the char-code # is the char# or 0~10.
thank you.

Answer
Hello James, thank you for the question.

Though there is no function to call to directly determine if a string is all numbers or not, you could use the function atoi() to figure it out. atoi() takes a string and converts it      to an integer. You could probably use a double for-loop to figure it out. Here is an example:

char str[] = "12345";

for(int i = 0; i < strlen(str) - 1; i++)
for(int j = 0; j <= 9; j++)
if(atoi(str[i]) == j)
// index is a number

So this goes index by index comparing each index to the numbers 0-9, which it would have to be if the string is all numbers. You could probably encapsulate that algorithm into a function if you wanted.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.