w3resource logo


C Programming Exercises

C Exercises: Convert a string to an integer

Secondary Nav

C Variable Type : Exercise-13 with Solution

Write a C program to convert a string to an integer.

Test Data and Expected Output :

Input a number : 1972                                                   
The value Input is 1972.

C Code:

#include<stdio.h>
#include<stdlib.h>

int main ()
	{
		int num1;
		char my_array [256];

		printf ("\nInput a number : ");
		fgets (my_array, 256, stdin);

		num1 = atoi (my_array);
		printf ("The value Input is %d.\n\n", num1);

		return 0;
	}
	

Solution

#include<stdio.h>
#include<stdlib.h>

int main ()
	{
		int num1;
		char my_array [256];

		printf ("\nInput a number : ");
		fgets (my_array, 256, stdin);

		num1 = atoi (my_array);
		printf ("The value Input is %d.\n\n", num1);

		return 0;
	}
	

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number