0

首先,请不要批评程序的编写方式,因为这是我们在我国学习的内容。

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

谢谢。

4

3 回答 3

1

在这份声明中

if (strcmp(a[i][j], a[n-1][j]) != 0)

这两个表达式a[i][j]a[n-1][j]具有 char 类型,而函数strcmp需要两个指向类型字符串的指针char *

所以编译器发出错误。

您可以使用标准函数简化您的第一个程序strncmp。例如

size_t p = strlen(a[n - 1]);
for (int i = 0; i < n - 1; i++)
{
    if ( strncmp( a[i], a[n-1], p ) == 0 ) cout << a[i] << " ";
}

请注意,您应该使用 header<cstring>而不是 header <string.h>

于 2020-04-29T15:32:53.593 回答
1
 int strcmp(const char *s1, const char *s2);

strcmp用来比较stringstring。但是在您的代码中,您比较charchara[i][j]a[n-1][j])。

在您的情况下,您可以使用它仅比较两个字符串strncmp的前(最多) n 个字节(在您的情况下, n is ):strlen(a[n-1])

int strncmp(const char *s1, const char *s2, size_t n);

因此,您的程序如下所示:

    for (int i = 0; i < n - 1; i++)
    {
        ok = 1;
        if (strncmp(a[i], a[n-1], p) != 0)
        {
            ok = 0;
        }
        if (ok == 1)
        {
            cout << a[i] << " ";
        }
    }
于 2020-04-29T15:21:57.313 回答
0

对问题中代码的最简单更改是将测试从 更改if (strcmp(a[i][j], a[n-1][j]) != 0)if (a[i][j] != a[n-1][j]).

于 2020-04-29T16:09:02.713 回答