198k views
2 votes
Write a function that converts a C-string into an integer. For example, given the string “1234” the function should return the integer 1234. If you do some research, you will find that there is a function named atoi and also the stringstream class that can do this conversion for you. However, in this program, do not use any predefined functions and you should write your own code to do the conversion. Use the function in your C++ program

User Rafaela
by
4.7k points

1 Answer

3 votes
#include
using namespace std;

// Our custom atoi function to make your teacher very happy ;)
int myAtoi(char* str)
{
int result = 0;

for (int i = 0; str[i] != '\0'; ++i)
result = result * 10 + str[i] - '0';

return result;
}
User Pete Karl II
by
5.1k points