1

编写此代码是为了从后面识别字符串中首先与给定字符匹配的字符位置。当我使用 scanf 获取字符串时,编译器不要求输入字符并直接将输出设为 0。我是无法纠正 scanf 的问题。

我通过直接提供字符串输入而不使用 scanf 来运行该函数,它工作正常。

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

int strrindex(char str[], char t)  
{   
int n=strlen(str);  

    while(n>=0)  
    {  
        if(str[n]==t)  
        {  
        return n;  
        }  
        else  
        {  
            n=n-1;  
        }       
    }
    return -1;
}  

int main()  
{  
    int k;  

    char str[100];  

    printf("enter line\n");  

    scanf("%s",str);  

    char t;  

    printf("enter letter\n");  

    scanf(" %c",&t);  

    k=strrindex(str,t);  

    int p=k+1;  

        printf("the position is %d",p);  
}  

代码运行,但输出始终为 0,主要是因为 scanf 添加了 \n。

4

1 回答 1

0

您包括了退货声明

return -1;  

在while循环中

while(n>=0)  
{  
    if(str[n]==t)  
    {  
    return n;  
    }  
    else  
    {  
        n=n-1;  
    }     
return -1;  
}

将其放在循环之外。

请注意该函数应声明为

size_t strrindex( const char str[], char t );

并在由于标准 C 函数的( size_t )-1返回类型为 而找不到字符的情况下返回。strlensize_t

请记住,有一个类似的标准 C 函数

char *strrchr(const char *s, int c);

这是一个演示程序

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

size_t strrindex( const char *s, char c )
{
    size_t n = strlen( s );

    while ( s[n] != c && n != 0 ) --n;

    return n == 9 ? -1 : n;
}


int main(void) 
{
    const char *s = "Hello";

    size_t n = strlen( s );

    do
    {
        size_t pos = strrindex( s, s[n] );

        if ( pos == -1 ) 
        {
            printf( "The character %c is not found\n", s[n] );
        }
        else
        {
            printf( "The character %c is found at position %zu\n", s[n] == '\0' ? '0' : s[n], pos );
        }
    } while ( n-- );

    return 0;
}

它的输出是

The character 0 is found at position 5
The character o is found at position 4
The character l is found at position 3
The character l is found at position 3
The character e is found at position 1
The character H is found at position 0

如果要从搜索中排除终止零,则该函数可以如下所示

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

size_t strrindex( const char *s, char c )
{
    size_t n = strlen( s );

    while ( n != 0 && s[n - 1] != c ) --n;

    return n == 0 ? -1 : n - 1;
}


int main(void) 
{
    const char *s = "Hello";

    size_t n = strlen( s );

    do
    {
        size_t pos = strrindex( s, s[n] );

        if ( pos == -1 ) 
        {
            printf( "The character %c is not found\n", s[n] == '\0' ? '0' : s[n] );
        }
        else
        {
            printf( "The character %c is found at position %zu\n", s[n] == '\0' ? '0' : s[n], pos );
        }
    } while ( n-- );

    return 0;
}

在这种情况下,程序输出是

The character 0 is not found
The character o is found at position 4
The character l is found at position 3
The character l is found at position 3
The character e is found at position 1
The character H is found at position 0

还要注意该函数scanf读取一个字符串,直到遇到一个空白字符。

所以而不是scanf使用fgets. 例如

fgets( str, sizeof( str ), stdin );
str[strcspn( str, "\n" )] = '\0';
于 2019-08-10T13:35:22.357 回答