【问题标题】:C Program to convert lowercase to uppercase char array without using other functions available in the C standard library [closed]在不使用 C 标准库中可用的其他函数的情况下将小写字符数组转换为大写字符数组的 C 程序 [关闭]
【发布时间】:2020-10-15 15:45:44
【问题描述】:

我试图用大写字母替换所有小写字母,而不使用 C 标准库中可用的其他函数和使用指针。 我有我的 main.c:

#include <stdio.h>
#include "upper1.h"

int main() {
    
        char string[] = "HelloWorld";
        int arraySize = sizeof(string) / sizeof(string[0]);
        printf("String before transformation: ");
        int i;
        for (i= 0; i< arraySize; i++) {
            printf("%c", string[i]); //prints array information
        } 
        printf("\n");
        
        char *str = string; //pointer that points to the array
        
        upper1(str);
        
        printf("String before transformation: ");
        int j;
        for (j= 0; j< arraySize; j++) {
            printf("%c", string[i]); //prints array information
        } 
        printf("\n");
        
        return 0;
}

我有我的功能代码文件:

void upper1(char *str) {
    int i;
    for(i = 0; i < 10; i++) {
        if(*str >= 65 + 32 && *str <= 90 + 32) { //65+32 is "a" and 90+32 is "z"
            *str = *str - 32;
        }
        str++;// skips one position of the array
    }
}

由于某种原因,当我跑步时,我得到:

gcc -g -Wall -c upper1.c -o upper1.o gcc -g -Wall -c main.c -o main.o gcc upper1.o main.o -o ex04 ./ex04 转换前的字符串:HelloWorld 转换前的字符串:����������

代替

gcc -g -Wall -c upper1.c -o upper1.o gcc -g -Wall -c main.c -o main.o gcc upper1.o main.o -o ex04 ./ex04 转换前的字符串:HelloWorld 转换前的字符串:HELLOWORLD

(我有一个文件“upper1.h”,但仅适用于:void upper1(char *str);

【问题讨论】:

  • 与问题无关,但您真的不应该在代码中使用幻数。如果您的意思是a,您应该使用a 而不是65+32。幻数使事情变得更难阅读。
  • printf("%c", string[i]); //prints array information 循环使用j 作为计数器。
  • 顺便说一句:arraySize 包括终止的 0 字节。您应该使用strlen 来获得正确的长度。
  • 在这种情况下,我正在使用 库,但我不能。这是锻炼规则。反正我解决了。这只是“main.c”中关于我的“for”cicle 使用错误索引(“i”而不是“j”)的错误。无论如何,我使用它来防止使用幻数:``` void upper1(char *str) { while(*str != '\0') { if(*str >= 'a' && *str
  • 您可以使用自己的strlen 版本。或者您可以将 arraySize 减一以跳过 0 字节。

标签: c pointers makefile uppercase lowercase


【解决方案1】:

这是因为您在第二个循环中使用了i 而不是j

printf("String before transformation: ");
int j;
for (j = 0; j < arraySize; j++) {
    printf("%c", string[j]); // use 'j' instead of 'i'
} 

您可以通过在 for 循环中声明循环计数器来避免以后出现这样的错字。这确保了计数器只能在循环范围内访问,并且不能在另一个循环中重用:

printf("String before transformation: ");
for (int j = 0; j < arraySize; j++) {
    printf("%c", string[j]);
} 

【讨论】:

    猜你喜欢
    • 2015-05-08
    • 2020-02-25
    • 2019-05-07
    • 2013-05-14
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多