Search⌘ K
AI Features

Challenge: Convert a String Into an Integer

Explore how to implement a function in C that converts a string of digits into an integer while detecting and returning an error for strings containing non-digit characters. This lesson helps you practice string traversal and validation techniques crucial for robust input handling.

Problem statement

In this challenge, you have to implement the stringToInt function.

int stringToInt(String str);

You are given the string, str, containing the integers in the input parameter. Your task is to convert a string representation of positive numbers like "124" into an integer, 124, and return it in the output.

📝 Note: If string, str, contains alphabets or special characters, then return -1 in the output.

Sample input

stringToInt(123)

Sample output

123

Coding exercise

Before diving directly into the solution, first, try to solve it yourself, and, then, check if your code passes all the test cases. If you get stuck, you can always see the given solution.

📝 Your function name should be the stringToInt. Otherwise, your code will not compile.

Good Luck! 👍

C
#include<stdio.h>
int stringToInt (char *str){
return 0;
}