简体   繁体   English

C:在字符串中查找特定字符

[英]C: Finding a specific character in a string

I am trying to write a program that searches for the first occurance of a specific character in a string.我正在尝试编写一个程序来搜索字符串中特定字符的第一次出现。 But no matter what character i type in the number the program gives back is the number of the last character.但无论我在数字中输入什么字符,程序返回的都是最后一个字符的数字。

int where (char *str, char ltr);

int main () {
    char word [80];
    char letter;
    printf("Type in a word: ");
    scanf("%s", word);
    printf("Type in a character: ");
    scanf("%s", letter);
    printf("%d", where(word, letter));
}

int where (char *str, char ltr){
    int i = 0;
    while(i < strlen(str)){
        if(ltr == str[i]){
            break;
        }
        i++;
    }
    return i;
}

The problem is that this here问题是这里

scanf("%s", letter);

Is undefined behavior because it's expecting a pointer to a character, but you give it a character.是未定义的行为,因为它需要一个指向字符的指针,但你给它一个字符。 The %s specifier is for reading strings, not single characters. %s说明符用于读取字符串,而不是单个字符。 Your compiler should warn you about a type mismatch here.您的编译器应该在此处警告您类型不匹配。

Instead, change it to this:相反,将其更改为:

scanf(" %c", &letter);

%c is for reading in single characters, and with the leading space you make it ignore any leading whitespace in the input (such as the newline entered after you word). %c用于读取单个字符,并使用前导空格使其忽略输入中的任何前导空格(例如在单词后输入的换行符)。

You should also change scanf("%s", word);您还应该更改scanf("%s", word); to scanf("%79s", word);scanf("%79s", word); in order to avoid undefined behavior when the user enters a very long word (this limits the word's length to your buffer's size).为了避免用户输入很长的单词时出现未定义的行为(这会将单词的长度限制为缓冲区的大小)。

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

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