gpt4 book ai didi

c - 打印字符串的中间字符

转载 作者:行者123 更新时间:2023-11-30 20:57:30 26 4
gpt4 key购买 nike

我必须用 C 语言编写一个程序,可以打印您输入的字符串的中间字母。空格()也会计算,并且字符数必须是奇数。

例如。输入

Hi sussie

--> 9 个字符,包括空格

输出应为s

我已经尝试过这个:

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

char x[100];


int main(void)
{
printf("Hello World\n");

scanf("%c\n",&x);

long int i = (strlen(x)-1)/2;
printf("the middle letter of the word is %c\n",x[i]);

return 0;
}

并且输出始终显示我输入的单词的第一个字母。

最佳答案

您仅从 stdin 读取第一个字符(这是错误的;您不应该使用 &)。

如果必须使用scanf,则应使用以下格式:

scanf("%99[^\n]", x);

这是安全的,不会读取超过缓冲区的内容。

请注意,%s 在这里不起作用。 %s 导致 scanf 将空格解释为字符串结尾。

更好、更安全、更简单的解决方案是使用 fgets 而不是 scanffgets 更安全,并且在更改数组大小时不需要更改格式字符串:

fgets(x, sizeof(x)-1, stdin);

这消除了任何可能的空白或缓冲区溢出问题。

关于c - 打印字符串的中间字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58821662/

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