193k views
4 votes
Write a C program that reads a string containing text and nonnegative numbers from the user and prints out the numbers contained in the string in separate lines. For example, if the input is: The year has 365 days and the day has 12 hours Then the output will be: 365 12

1 Answer

3 votes

Here is the code in C.

#include <stdio.h>

#include <string.h>

//main function

void main()

{

// character array to store the string

char str[1000];

int len,i,j;

char c,ch;

printf("Please Enter a string: ");

// read the string

gets(str);

// find the length of input string

len = strlen(str);

for(i=0;i<len;i++)

{

c=str[i];

// if any character of string is digit then it will check

// until it finds the next non-digit character

if(c>='0' && c<='9')

{

for(j=i;j<len;j++)

{

ch=str[j];

if(ch>='0' && ch<='9')

//print the number in the string

printf("%c",str[j]);

else

{

printf(" ");

i=j;

break;

}

}

}

}

}

Step-by-step explanation:

First it ask user to input a string and store that string into character array.Then travers the array and find first digit character.If a digit is found then print that digit.After that in the inner for loop, check next character is digit or not, if a digit meets then print that digit.Repeat this until the next non-digit character founds.When a non-digit character meets print a space and update the value of "i" and break the inner loop.It will again check the same from the ith index in the character array.

Output:

Please Enter a string: The year has 365 days and the day has 12 hours

365 12

User Rossco
by
5.3k points