首先,请不要批评程序的编写方式,因为这是我们在我国学习的内容。
我知道它是 C 和 C++ 的混合体,而且我使用的东西已经过时,但事情就是这样。
所以我必须制作一个程序,将 n 个单词作为输入。然后我必须打印以最后一个作为前缀的单词。
例如
input:
n=6
raita grai raid raion straie rai
output:
raita raid raion
这是我的程序。它按预期工作:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int n;
char a[100][100];
bool ok=1;
cin >> n;
cin.get();
for (int i = 0; i < n; i++)
{
cin.get(a[i], 100);
cin.get();
}
int p = strlen(a[n - 1]);
for (int i = 0; i < n - 1; i++)
{
for(int j = 0; j < p; j++)
{
ok = 1;
if ((unsigned int)a[i][j] != (unsigned int)a[n-1][j])
{
ok = 0;
break;
}
}
if (ok == 1)
{
cout << a[i] << " ";
}
}
}
但最初,它看起来像这样:
/* strstr example */
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int n;
char a[100][100];
bool ok=1;
cin >> n;
cin.get();
for (int i = 0; i < n; i++)
{
cin.get(a[i], 100);
cin.get();
}
int p = strlen(a[n - 1]);
for (int i = 0; i < n - 1; i++)
{
for(int j = 0; j < p; j++)
{
ok = 1;
if (strcmp(a[i][j], a[n-1][j]) != 0)
{
ok = 0;
break;
}
}
if (ok == 1)
{
cout << a[i] << " ";
}
}
}
它会引发一些错误:
Severity Code Description Project File Line Suppression State
Error (active) E0167 argument of type "char" is incompatible with parameter of type "const char *" ConsoleApplication1 25
Severity Code Description Project File Line Suppression State
Error C2664 'int strcmp(const char *,const char *)': cannot convert argument 1 from 'char' to 'const char *' ConsoleApplication1 25
我似乎无法理解为什么会发生这种情况。你们中的任何人都可以帮助我理解吗?另外,我应该使用转换为 (unsigned int) 还是只使用 strcmp?
谢谢。