gpt4 book ai didi

遍历字符串并标记非字母的 C 程序

转载 作者:行者123 更新时间:2023-12-01 18:04:32 26 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序,它遍历一串字符,如果通过命令行给定参数则打印出“NON-LETTER”。

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

int main(int argc, char **argv)
{
int i = 0;
for (i = 1; i < argc; i++){
if (!isalpha(argv[i])){
printf("NON-LETTER\n");
}
}

return 0;
}

但是我遇到了段错误。这是因为我正在与 isalpha() 进行比较吗?看起来 argv[i] 是一个字符串?

最佳答案

argv[i] 是指向第 i 个参数(字符串)的 char *,而 isalpha需要一个表示为 int1 的字符。

这里发生的是你正在传递一个指针,它被隐式转换为 intisalpha 试图将它解释为一个字符(可能是一个索引查找表),一切都会爆炸(从技术上讲,这是未定义的行为)。

您可能想要做的是逐个字符地检查每个参数,例如:

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

int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
for(int j = 0; argv[i][j] != '\0'; ++j) {
if (!isalpha((unsigned char)argv[i][j])) {
printf("NON-LETTER\n");
}
}
}
return 0;
}

  1. 特别是,char 值转换为 unsigned char 转换为 intdue to unfortunate reasons I detailed elsewhere .

关于遍历字符串并标记非字母的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59605783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com