gpt4 book ai didi

c - 为什么我的输出为空?

转载 作者:行者123 更新时间:2023-11-30 15:04:43 25 4
gpt4 key购买 nike

#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;
}

程序的输入是“我的名字是Steve”,并且该程序的输出变为,M之后的字符串是(null)为什么会发生这种情况?

最佳答案

正如评论之一中提到的,scanf("%s", str) 读取直到找到尾随空格。在您输入的“My name is Steve”中,scanf 将读取到 My,因为 My 后面有一个空格。

Assuming that your input only contains numbers,letters, and spaces you could try the following:

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;
}

If you are not required to use scanf(), I will recommend staying away from scanf() and using fgets() instead:

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;
}

关于c - 为什么我的输出为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com