-
C++help
hi guys,
could you please help me with my C++ question
i have to do it until April 11.
i did it but i'm not sure if it's right
Here is my program question:
Write a function that takes a string and tries to turn it into a
positive integer value. If the string has any characters that are not digits then return -1, otherwise return the integer value of the string. For example, for the string "12345" return the int 12345. For the string "12a45" return -1. For the string "-23" return -1, since the dash character('-') is not a digit.
Here is the function declaration:
int stringToPositiveInt(char s[ ]);
This is what i did but i'm really confused about my program:
int stringToPositiveInt(char s[ ])
{
if (strcmp(s, "12345") == 0)
return s;
else if (strcmp(s, "12a45") == 0)
return -1;
else
return -1;
}
I would greatly appreciate for your help
my best regards
albina
-
Confused
What you did is not a general way, your function only works (and it doesn't even work ) for the input "12345" and "12A45".
This is what you should do:
1)
Look through all characters in the string, this can be done easily with a for loop and strlen().
If one of the characters is not a number (ASCII value 48-57), then return -1.
2)
Make an integer value of the string. The easiest way would be to use atoi().
You could also go through the string backwards and multiply the last number with 1, second last number with 10, third last number with 100 and so on, and then sum all these numbers together and return this number.
I could write the whole program for you, but that would probably do you more harm than good .
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
-
C++help
Hi Magos,
Thank you so much for your quick response and
great solutions.
regards
albina
Popular pages
Recent additions