I'm writing a function to capitalize every lowercase character in a string. It takes a string from the user and that is the input to the function. My program works if the user doesn't enter spaces, but when there is a space in the string, the function ends.
#include <stdio.h>
char *uppercase(char *c) {
int i = 0;
while (c[i] != '\0') {
if (123 > c[i] && c[i] > 96)
c[i] = c[i] - 'a' 'A';
i ;
}
return c;
}
int main() {
char input[100];
printf("Enter the phrase: ");
scanf("%s", input);
printf("%s", uppercase(input));
return 0;
}
Examples:
Input: test test
Output: TEST
Input: Hello
Output: HELLO
Input: How are you
Output: HOW
I think it has to do with the while
statement? Thanks for the help.
CodePudding user response:
The problem is not in the while
statement, but rather due to the scanf()
format: %s
reads a single word from the input, leaving the rest of the line in the stdin
buffer. Note also that typing a word with more than 99 characters will cause undefined behavior because scanf()
will write beyond the end of the input
array. Using