-3

I want to make a simple toupper coding on my Laptop (windows 7). It appears that anything i wrote it only capitalize 1 word in the beginning.

Whether i use %s / %c / %[^\n]

What am I suppoused to do?

Im using Microsoft Visual C++ 2010 Express

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

int main()
{
    char kalimat;
    scanf ("%[^\n]",&kalimat);
    kalimat=toupper(kalimat);
    printf("%s",kalimat);
    getchar ();
    return(0);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

1

You want to read a word. For this, you need an array of char of some pre-defined size. So change

char kalimat;

to

char kalimat[64]; /* Can hold 63 chars, +1 for the NUL-terminator */

Next, you want to scan a word. So change

scanf("%[^\n]",&kalimat);

to

scanf("%63s", kalimat);

The changes made here are

  1. Usage of %s used to scan a word as opposed to %c which is used to scan a character.
  2. Removing the ampersand because %s expects a char*, not a char** or char(*)[64].
  3. Using a length specifier (63, here) in order to prevent a buffer overflow.

Then, if you want to

  1. Captalize the first character of the array/word, use

    kalimat[0] = toupper(kalimat[0]);
    

    or

    *kalimat = toupper(*kalimat);
    
  2. Capitalize all characters in the array, use a loop calling toupper on each index of the array:

    int i, len; /* Declare at the start of `main` */
    
    for(i = 0, len = strlen(string); i < len; i++) /* Note: strlen requires `string.h` */
        kalimat[i] = toupper(kalimat[i]);
    

But... you might need to change

getchar ();

to

int c; /* Declare at the start of `main` */
while((c = getchar()) != EOF && c != '\n');

in order to prevent the consle from closing.


Fixed code:

#include <stdio.h>
#include <ctype.h>
#include <string.h> /* For `strlen` */

int main()
{
    int i, len, c;
    char kalimat[64];

    scanf ("%63s", &kalimat);

    /* `*kalimat = toupper(*kalimat);` */
    /* or */
    /* `kalimat[0] = toupper(kalimat[0]);` */
    /* or */
    /* `for(i = 0, len = strlen(string); i < len; i++) 
        kalimat[i] = toupper(kalimat[i]);` */

    printf("%s", kalimat);

    while((c = getchar()) != EOF && c != '\n');
    return(0);
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

The C library function :

int toupper(int c);

converts a lower case letter to its uppercase

If you want to print all letters of a string to it's upper case :

int i=0;
while(str[i])
{
 putchar (toupper(str[i]));
 i++;
}

However for capitalising a single character you could simply use:

 putchar (toupper(mychar));

The function returns uppercase if there exists one or returns the same character sent to it.

In C you could store a string :

 char *string1="Elvis";
 char string2[]="Presley";
 char string3[4]="King";
Rahul Jha
  • 1,131
  • 1
  • 10
  • 25