【发布时间】:2020-02-10 14:37:56
【问题描述】:
Q. 输入并存储 n 个字符串,然后搜索特定字符串。
我可以输入“字符串数”,然后我也可以输入字符串。但是字符串不会被打印出来。比较和搜索都没有发生,它显示了一个分割错误。当我使用 gets() 输入字符串时会发生这种情况。 但是当我使用 scanf() 输入字符串时,程序会在我输入“字符串数”后立即终止。为什么会这样?
代码如下:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[200],names[100];
int n,i;
int flag=0;
printf("Give number of strings:\n");
scanf("%d",&n);
printf("Enter the strings:\n");
for(i=0;i<n;i++)
{
gets(names);
}
printf("Entered Values are:\n");
for(i=0;i<n;i++)
{
printf("%s\t",names[i]);
}
printf("Enter the string you want to search for:\n");
scanf("%s",str);
for(i=0;i<n;i++)
{
if(strcmp(names[i],str) == 0)
{
flag=1;
break;
}
}
if(flag==1)
printf("Yes this string %s exists!\n",str);
else
printf("No it does not exists");
return 0;
}
【问题讨论】:
-
这段代码应该给你各种类型不匹配的警告,尤其是关于在预期
char*的地方使用char。先修好那些。提示:names[100]是 一个 字符串,而不是字符串数组。 -
Blaze 建议您打开编译器的警告(并听取它已经报告的错误)。
-
他们所说的,而且永远不要使用
gets。也不要使用conio.h。 -
for循环内的
gets(names);如何将读取的字符串放入names数组的条目中(假设它是一个字符串数组)? -
请参阅scanf() leaves the newline char in the buffer。另请注意,
gets已过时,您不应混合使用不同类型的输入函数。