Reputation: 19
I am trying to design a simple program which will ask the username, but when the entered username is later used, it should have its first letter uppercase.
How can I do that?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main() {
char name[30];
printf("What is your name?\n");
scanf("%s", name);
char n = toupper(name);
printf("Hello %s. Could you tell us a bit about yourself?", n);
}
Upvotes: 0
Views: 74
Reputation: 26763
This is an answer which attempts to get your code working with minimal changes.
Change
toupper(name);
to
toupper(*name);
in order to correctly use only the first character of the name, which is what name
, interpreted as pointer to char
points to.
Then change
printf("Hello %s. Could you tell us a bit about yourself?", n);
tp
printf("Hello %c%s. Could you tell us a bit about yourself?", n, name+1);
in order to print first the modified first character and then the rest of the name, employing pointer arithmetic (again interpreting name
as pointer to char) to skip the first character.
Upvotes: 0
Reputation: 2658
If you have collected the name, you can proceed as follows:
if (name[0] >= 'a' && name[0] <= 'z')
{
name[0] -= 0x20;
}
printf("Hello %s. Could you tell us a bit about yourself?", name);
The assumptions are:
1 - you have the name
2 - it begins in first character of the character array
3 - the name is in ASCII / English 7-bit characters
Aside from that, see the other answer by Pablo - you've made several errors.
Upvotes: 0
Reputation: 13590
This line is wrong
char n = toupper(name);
The function toupper
expects a single character, you are passing a pointer
to a character.
The correct version:
char n = toupper(name[0]);
This line is also wrong
printf("Hello %s. Could you tell us a bit about yourself?", n);
The format specifier %s
expects a string passed by a pointer of char
, you
are passing a single character. The compiler should have warned you about it.
Don't ignore the compiler warnings.
You want to change the first letter in the buffer. So you have to save the converted letter back into the buffer.
name[0] = toupper(name[0]);
printf("Hello %s. Could you tell us a bit about yourself?", name);
Upvotes: 2