Reputation: 250
My code is correct as I can see it has no errors at all, but when I execute it and say for instance I type in "MY NAME IS JACK" it only converts "MY" to lowercase.
#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
int i;
printf("Enter any string->");
scanf("%s",&str);
for(i=0;i<=strlen(str);i++){
if(str[i]>=65&&str[i]<=90)
str[i]=str[i]+32;
}
printf("\nThe string in lower case is->%s",str);
return 0;
}
Upvotes: 0
Views: 1125
Reputation: 123558
As others have pointed out, scanf
using the %s
conversion specifier will stop reading intput at the first whitespace character. If you want to read in the whole line, use fgets
instead:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
...
if ( fgets( str, sizeof str, stdin ) != NULL )
{
/**
* chop off the newline if it's present
*/
char *newline = strchr( str, '\n' );
if ( newline )
{
*newline = 0;
}
/**
* Convert the string to lower case.
*/
for ( int i = 0; str[i] != 0; i++ )
str[i] = tolower( str[i] );
}
Note - if there isn't a newline in the buffer, that means that the user typed in a string that was longer than the buffer could hold, meaning there's leftover data in the input stream. You'll probably want to issue a warning and consume that leftover input (usually by repeatedly calling fgets
or getchar
and stopping when you see a newline character).
Upvotes: 3
Reputation: 5232
Change
scanf("%s",&str);
to
scanf("%[^\n]",str);
and your code should work. %s
reads until whitespaces. Using [^\n]
makes scanf read into the str variable until it encounters a newline. Also, don't pass the address of str
, just str
itself.
Upvotes: 0
Reputation: 68
You can try the following code for it as well once you are done with your input.
void convertToUpperCase(char *sPtr)
{
while(*sPtr != '\0')
{
if (islower(*sPtr))
*sPtr = toupper(*sPtr);
}
}
Upvotes: 1
Reputation: 986
First,
scanf()
expects argument of type 'char ' but you are passing char ()[20]. Just pass 'str'.
Second,
This is just suggestion. Try to use isalpha()
or issuper()
, islower()
Upvotes: 0
Reputation: 4069
The scanf description for the %s
format defines it as:
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
So you are asking for the first non-whitespace text within str
, which is "MY". Once it hits that space, it stops.
What would be better for your usage: reading the entire line in at once, or putting your scanf
into a loop so you can read successive words?
Upvotes: 1