-1

I am trying to use a for loop with ASCII table to make every character in the string uppercase one by one by subtracting the letter number with 32. but I cant use the int i in the char str and str2. how can I do this?

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

#define STRLEN 200

void string_lower() {

}

void string_upper(char str) {
    char str2;
    
    int length = strlen(str);
    for (int i = 0; i < length; i++) {
        str2[i] = str[i - 32];
    }
}

int main() {
    char word[STRLEN] = { 0 };
    char word1 = 97;

    printf("Write a word");
    fgets(word, STRLEN, stdin);

    string_upper(word);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

5

You can use toupper() to uppercase one character at a time. This will work for single byte character sets such as ASCII, but not for the UTF-8 encoding in general use today for non English scripts.

Here is a modified version:

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

#define STRLEN 200

char *string_upper(char *str) {
    for (size_t i = 0; str[i] != '\0'; i++) {
        str[i] = toupper((unsigned char)str[i]);
    }
    return str;
}

int main() {
    char word[STRLEN];

    printf("Enter a word: ");
    if (fgets(word, STRLEN, stdin)) {
        printf("%s", string_upper(word);
    }
    return 0;
}

The argument must be cast as (unsigned char)str[i] because str[i] has type char and tolower() like all functions and macros from <ctype.h> is only defined for values of the type unsigned char and the special negative value EOF. As char may be signed on some platforms, passing it directly to tolower() would have undefined behavior for negative values such as 'é' and 'ÿ'.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

If you just want to make a function to convert your String to upper, maybe you can refer to the below example.

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

#define STRLEN 200

void string2upper(char *str){
    int cursor=0;

    while(*(str+cursor)!='\0'){
        *(str+cursor) = toupper(*(str+cursor));
        cursor++;
    }
}

void main() {

    char String1[STRLEN];
    printf("Write a word:\n");
    fgets(String1, STRLEN, stdin);

    printf("Before : %s\n", String1);
    string2upper(String1);
    printf("After : %s\n", String1);

}

For the toupper() function, I think you can refer to this Link.

That has a detailed explanation and simple example to understand.

I think to know the function detail is better than only using~

jackieBB
  • 126
  • 1
  • 2
  • 3