【问题标题】:Error: Expected expression before 'String' And too few arguments to function 'strcmp'错误:“字符串”之前的预期表达式和函数“strcmp”的参数太少
【发布时间】:2021-03-27 04:16:18
【问题描述】:

我一直在尝试为我们的分组完成程序的一部分,但每当我尝试编译时,这部分代码总是出错。

int
Binary_Search(String key, String Name[], int nElements)
{
    /* Implement the body of this function. */
    
    int position;
    int begin = 0; 
    int end = String Name - 1; //Error: Expected expression before 'String'
    int result = 0;
    
    while(begin <= end) 
    {
        position = (begin + end) / 2;
        if(result = strcmp(String Name, nElements) == 0) //Error: Expected expression 
                                                 //before 'String'
                                                 // too few arguments to 
                                                 // Function 'strcmp'
            return position;
    
        else if(result < 0)
            begin = position + 1;
    
        else
            end = position - 1;
    }
}

【问题讨论】:

  • 什么是String?你从哪里得到错误?请edit您的问题不仅包括完整和完整的错误输出,复制粘贴为文本,还请尝试包括导致错误的minimal reproducible example,并在您获得它们的行上添加cmets。
  • 作为关于您的问题的提示,请返回您的教科书(如果没有,请查阅)并阅读有关数组和指针的更多信息。
  • 对不起@Someprogrammerdude,我对编程很陌生,而且通过在线课程,我学习编程有点困难
  • strcmp(String Name, nElements) 的两个概率 a) 传递参数时不能提及类型,b) 第二个参数也必须是字符串,而不是整数。
  • 另一个问题是分配给result 的布尔值。它不能是&lt; 0,因为在下面的测试中(尽管来自strcmp() 的返回值可以)。我认为你应该多研究strcmp()。

标签: c string binary-search strcmp


【解决方案1】:

首先,end 应该设置为nElements-1。

那么这行有几个问题:

if(result = strcmp(String Name, nElements) == 0)

最明显的是它应该是strcmp(Name, nElements),假设String是char*的一些可怕的typedef(来自像CS-50这样的坏类?)。

另外,nElements 是一个int,而不是一个字符串,所以它不能与一个字符串进行比较......据说你打算做类似strcmp(Name[position], key) 的事情。

另一个问题是result 被分配了表达式strcmp(...) == 0(给出1 或0)的结果,而不是strcmp(&lt;0,或==0,或&gt;0) 如您所愿。出于这个原因,在控制/循环语句中使用= 是不好的做法,它总是会导致错误。您应该将代码更改为:

result = strcmp(Name[position], key);

if(result == 0)
    return position;
else if(result < 0)
    begin = position + 1;
else // if result > 0
    end = position - 1;

【讨论】:

  • 总结:你不能通过“冒险”/反复试验来编程。你必须真正知道你写的每一行是做什么的,没有猜测。
【解决方案2】:

我们在 c 中没有字符串数据类型。 尝试使用 char 数组来解决您的问题。 strcmp 还用于比较 char 数组(即字符串)而不是字符串与 int。

【讨论】:

  • 这很可能来自可怕的 CS-50 课程,哈佛大学教学生使用不良做法typedef char* String;。
  • 那没关系,但是你不能使用 string cmp 比较 string 和 int
猜你喜欢
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多