For starters the function main
shall have explicitly specified return type int
(or compatible)
int main( void )
As for your question then according to the C Standard (7.21.6.2 The fscanf
function; the same is valid for scanf
)
s
Matches a sequence of non-white-space characters.
That is as soon as a white space character is encountered filling of the corresponding character array used as an argument expression is stopped. The read sequence of non white space characters is ended with a null character '\0'
. Thus only the first word 123
from user input is read and reversed by the program, the rest of the input line would be read by another call to scanf()
if you had a loop.
If you want to read strings that contain embedded white space characters, then you need to use another conversion specification as for example:
scanf(" %29[^\n]", given);
Pay attention too that calling the function strlen
several times is inefficient.
Also you should declare variables in minimum scopes where they are used.
Your program can look the following way
#include <stdio.h>
#include <string.h>
int main( void )
{
char given[30];
char reversed[30];
printf( "enter your string: " );
if ( scanf(" %29[^\n]", given) == 1 )
{
size_t n = strlen( given );
reversed[n] = '\0';
for ( size_t i = 0; i < n; i++ )
{
reversed[i] = given[n - 1 - i];
}
puts( reversed );
}
return 0;
}