Strcmp无法正常工作,我似乎也不明白为什么-转换为ASCII代码可以使程序按预期方式工作]] << [

问题描述 投票:0回答:2
首先,请不要批评程序的编写方式,因为这是我们在我国学习的内容。

我知道这是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?

谢谢。

首先,请不要批评程序的编写方式,因为这是我们在我国学习的内容。我知道它是C和C ++的混合体,我使用的东西已经过时,但这就是...

c++ for-loop c-strings strncmp floppy
2个回答
0
投票
int strcmp(const char *s1, const char *s2);

0
投票
在此声明中
© www.soinside.com 2019 - 2024. All rights reserved.