在此代码中不使用 gets(c) 和 gets(s) 的替代方案是什么?



编辑:

问题:

编写一个程序来查找给定单词(即短字符串)在 句子(即长字符串!从标准输入读取数据。第一行是一个单词,它 后跟第二行的一般文本。

示例输入:

the
the cat sat on the mat

示例输出:

2

我之前尝试使用 scanf,但它无法读取整个句子,只是检查第一个单词并返回 1 而不是 2 作为答案

代码为:

#include <stdio.h>
#include <string.h>
int main()
{
char s[200000], c[20], v = ' ';
int i = 0, j, f, n = 0;
gets(c);
gets(s);
while (i < strlen(s))
{
j = 0;
f = 0;
while (j < strlen(c))
{
if (s[i++] != c[j++])
{
f = 1;
i--;
break;
}
}
if ((f == 0) && (i == strlen(s) || s[i] == ' ') && (v == ' '))
{
n++;
v = s[i++];
}
printf("%dn", n);
return 0;
}
}

这是您尝试实现的程序的解决方案(答案)。这也提供了获取字符串的正确方法。

希望这对任何一种方式都有帮助!

在此代码中不使用 gets(c) 和 gets(s) 的替代方案是什么?

代替char c[20]; gets(c);,请使用以下内容

// Read a line of text
char c[20+1];  // 1 more for the n
if (fgets(c, sizeof c, stdin) == NULL) {
// Handle EOF or input error in some fashion
puts("Unexpected EOF or input error");
return 1;
}

删除'n'从 fgets() 输入中删除尾随换行符

// lop off a potential trailing 'n'.
c[strcspn(c, "n")] = '';

其余代码可能仍有其他问题。

最新更新