Hi everyone so I have started learning strings in c and I get a problem. I have been changing initialized strings to uppercase or lower case and its easy. But I am having some trouble changing user input to uppercase. Here is a simple program which will take user input and count the string length and is suppossed to also capitalize the input.
Thanks Guys!!

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, const char * argv[])
{
    char name[10];
    int x = 0;

    //get user input of name
    printf("Enter your name: ");
    scanf("%s",&name[10]);

    printf("Your name has %lu letters.", strlen(&name[10]));//Length


    //Having problem over here I need to print the string in uppercase
    for ( x = 0; x < strlen(&name[10]) ; x++){


    printf("%c",toupper(name[x]));

    }

    return 0;
}

Can't test at the moment, but try this.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, const char * argv[])
{
    char name[10];
    int x = 0;
    //get user input of name
    printf("Enter your name: ");
    scanf("%s",&name[10]);
    printf("Your name has %lu letters.", strlen(&name[10]));//Length
    //Having problem over here I need to print the string in uppercase
    char cr;
    for ( x = 0; x < strlen(&name[10]) ; x++){
    cr = name[x];
    printf("%c",toupper(cr));
    }
    return 0;
}

Edited 2 Years Ago by Suzie999

lines 10, 14 and 18 are incorrect. What you did was pass a pointer to a non-existant byte in the string. This is how it should have been coded:
scanf("%s",name);

Notice it does not need the & address operator because arrays are always passed by address. That passes the address of the first byte of the string.

Another point about that program -- unless the length of the string can change during the loop you should call strlen() only once, save it in a variable, then use that variable in the loop. Calling strlen() on each loop iteration consumes too much CPU time.

int len = strlen(name);
 for ( x = 0; x < len; x++){

Edited 2 Years Ago by Ancient Dragon

This article has been dead for over six months. Start a new discussion instead.