我刚开始使用 C,但我的代码中存在段错误(顺便说一句,这很简单),我遇到了困难。 本练习的目标是将字符串中的每个字母大写。 有人可以帮我吗?
这里是作业:“编写一个函数,将其中每个单词的每个字母都变成大写”(我们必须手动完成,不使用其他库方法)。
这里是错误信息:“[1] 14328 segmentation fault (core dumped) ./a.out”
#include <stdio.h>
#include <unistd.h>
char *my_strupcase(char *str) {
int index = 0;
for (index = 0; str[index] != '\0'; index++) {
if ((str[index] >= 'a' && str[index] <= 'z') || (str[index] >= 'A' && str[index] <= 'Z')) {
str[index] = (str[index] - 32);
printf("%c \n", str[index]);
}
}
return str;
}
int main() {
my_strupcase("salut");
return (0);
}
最佳答案
这是一个带有注释的更正版本:
#include <stdio.h>
// you don't need unistd.h
char *my_strupcase(char *str) {
for (int index = 0; str[index] != '\0'; index++) { // declare index here
// as it's not used anywhere else
if ((str[index] >= 'a' && str[index] <= 'z') { // only process a-z
str[index] = str[index] - ('a' - 'A'); // 'a' - 'A' is more clear then 32
printf("%c \n", str[index]);
}
}
return str;
}
int main() {
char mytext[] = "salut HELLO 123"; // here mytext is an array of char
my_strupcase(mytext); // that can be modified.
puts(mytext);
return (0);
}
输出应该是:
SALUT HELLO 123
您的程序出现段错误是因为您试图修改字符串文字;这是未定义的行为,会导致许多平台上的程序崩溃。您可以在以下 SO article 中找到有关此的更多详细信息.
请注意,大写通常应使用标准函数(例如 toupper
)完成。
关于使用ascii在C中大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58453519/