0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(){

    char str [1000] = "";
    char ch     = 'M';
    char *findM;
        printf("Enter a line of text\n");
        scanf("%s", str);
            findM = strchr(str, ch);
        printf("string after %c is %s ", ch, findM);

    return 0;
}

程序的输入是"My name is Steve",而这个程序的输出变成, M 之后的字符串是 (null) 为什么会出现这种情况?

4

4 回答 4

1

正如其中一条评论中提到的,scanf("%s", str)读取直到找到尾随空格。在您的输入中,“我的名字是史蒂夫”scanf将读取到,My因为 . 后面有一个空格My

假设您的输入仅包含数字、字母和空格,您可以尝试以下操作:

int main() 
{
    char str[1000] = "";
    char ch = 'M';
    char *findM;
    printf("Enter a line of text\n");
    scanf("%999[0-9a-zA-Z ]", str); // Get all alphanumerics and spaces until \n is found
    findM = strchr(str, ch);
    findM++; // Increment the pointer to point to the next char after M
    printf("string after %c is %s ", ch, findM);

    return 0;
}

如果您不需要使用scanf(),我建议您远离scanf()fgets()改用:

int main()
{

    char str[1000] = "";
    char ch = 'M';
    char *findM;
    printf("Enter a line of text\n");
    fgets(str, sizeof(str), stdin); // Get the whole string
    findM = strchr(str, ch);
    findM++; // Increase the counter to move to the next char after M
    printf("string after %c is %s ", ch, findM);

    return 0;
}
于 2016-10-23T02:36:46.720 回答
0

strchr()正在考虑将“”(空格)作为分隔符,因此请在没有空格的情况下给您输入,它可以正常工作..

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

int main()
{

    char str [1000] = "";
    char ch     = 'M';
    char *findM;
    printf("Enter a line of text\n");
        scanf("%s", str);
        findM = strchr(str, ch);
    if(findM)
            printf("string after %c is %s ", ch, findM);

    else
        printf("Character not found ...\n");
    return 0;
}
于 2016-10-23T06:45:18.313 回答
0

如果该方法找不到任何匹配项,您将得到 null,您的输入可能没有“M”

更多详情:http ://www.cplusplus.com/reference/cstring/strchr/

于 2016-10-22T23:13:26.780 回答
0

可能您的 str 变量在第一个单词中不包含 char 'M' - 如果未找到匹配项,则 strchr(string, char) 函数返回 null 并在第一个空格(不包括前导空格)之后切断输入字符串。正如 user3121023 在他们的评论中提到的,使用 fgets 来捕获多词输入。

于 2016-10-22T23:13:27.687 回答