【发布时间】: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