Question

4. Write a C function int str2int(char *s) that takes string s as parameter and return the integer that s represents. For example, if string s is 123, then the function return integer 123.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <string.h>
#include <stdio.h>

#define MAX 100

int str2int(char* s)
{
    int i, len = strlen(s);
    int result = 0;
    for (i = 0; i < len; i++) {
        result *= 10;
        result += (s[i] - '0');
    }
    return result;
}

int main()
{
    char str[MAX];
    printf("Enter string: ");
    scanf("%s", str);
    printf("Output: %d ", str2int(str));
    return 0;
}

nter string: 12345 Output: 12345 Process exited after 2.665 seconds with returnvalue 0 Press any key to continue - - -

Please upvote the solution if it helped. Thanks!

Add a comment
Know the answer?
Add Answer to:
4. Write a C function int str2int(char *s) that takes string s as parameter and return...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT