[用户输入字符串中最后一个字符的ASCII值输出(使用fgets)为10,而期望值为0

问题描述 投票:-2回答:1

我正在编写一个模拟strcmp()的程序。这是我的代码。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 100
int strcmp(const char *str1, const char *str2);

char s1[MAX], s2[MAX];

int main()
{
    printf("Compare two user entered strings character by character.\n");
    printf("Enter string one: ");
    fgets(s1, MAX, stdin);
    printf("Enter string two: ");
    fgets(s2, MAX, stdin);
    printf("The user entered string one is: %s", s1);
    printf("The user entered string two is: %s", s2);
    printf("The value returned by strcmp() is: %d", strcmp(s1, s2));
    return 0;
}

int strcmp(const char *str1, const char *str2){
    int result;
    while(*str1 != '\0' && *str1 - *str2 == 0){
            str1++;
            str2++;
    }
    if(*str1 - *str2 != '\0'){
            printf("%d\n", *str1);
            printf("%d\n", *str2);
            result = *str1 - *str2;
        }else if(*str1 == '\0' && *str2 == '\0'){
            result = 0;
        }

    return result;
}

在大多数情况下,它工作正常,并且strcmp()函数返回正确的结果,除非一个字符串终止并且另一个字符串剩余字符。我使用while循环比较字符并将指针增加到下一个字符。当字符串增加到“ \ 0”时,在执行printf时显示的整数值为10。为什么它不是0?因为该值为10,所以从中减去其他字符串的字符得到的结果大10。

为什么会这样?

c string pointers null fgets
1个回答
2
投票

如果目标字符数组中有足够的空间,则功能fgets可以将换行符'\n'-十进制10(对应于Enter键)附加到输入的字符串。

您应该删除它。例如

#include <string.h>

//...

fgets(s1, MAX, stdin);
s1[ strcspn( s1, "\n" ) ] = '\0'; 
printf("Enter string two: ");
fgets(s2, MAX, stdin);
s2[ strcspn( s2, "\n" ) ] = '\0'; 
© www.soinside.com 2019 - 2024. All rights reserved.