繁体   English   中英

我在 c 中使用 isalnum() 做错了什么?

[英]What am I doing wrong with isalnum() in c?

该代码应该允许用户编写一个短语,计算有多少个字符并判断它是否是字母数字,但是即使我使用“+”或排序,字母数字字符的计数器也会上升。 我究竟做错了什么?

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

#define MAXR 100
#define MAXC 10     
#define TERMINATOR "END"

int main() {

    char phrase[MAXR];
    char text[MAXC][MAXR];
  
    int i;
    int countalnum = 0;
    int countchar = 0;

    for (i = 0; i < MAXC; i++) {
  
        fgets(phrase, MAXR, stdin);
        phrase[strlen(phrase) - 1] = '\0';
    
        for (int j = 0; j < strlen(phrase); j++) {
            countchar++;
            if (isalnum(phrase[i]) == 0)
                countalnum++;
        }
    
        if (strcmp(phrase, TERMINATOR) == 0) {
            exit(0);
        }
    
        strcpy(text[i], phrase);
    }
    ...
}

如果我不够清楚,请随时告诉我,以便我可以尝试更好地向您解释

@Cid 和@xing 评论都是正确的。 您需要更改isalnum()条件,并且在应该是j的地方使用了i

下次只需添加一些调试打印并查看流程,您将很快找出哪里出错了。

这是一个固定版本。

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

#define MAXR 100
#define MAXC 10     
#define TERMINATOR "END"

int main()
{
    char phrase[MAXR];
    char text[MAXC][MAXR];
  
    int i;
    int countalnum = 0;
    int countchar = 0;

    for (i = 0; i < MAXC; i++) {
  
        if (!fgets(phrase, MAXR, stdin))
            break;

        int len = strlen(phrase); // better to cache this value
        // strip the trailing newline if any
        if (len > 0 && phrase[len - 1] == '\n')
            phrase[--len] = '\0';

        if (strcmp(phrase, TERMINATOR) == 0) {
            break;
        }   
    
        for (int j = 0; j < len; j++) {
            countchar++;
            if (isalnum((unsigned char)phrase[j]))
                countalnum++;
        }
    
        strcpy(text[i], phrase);
    }

    // The result doesn't include the terminator "END"
    printf("Total chars: %d\n", countchar);
    printf("Total alphanumeric chars: %d\n", countalnum);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM