C ++中的参数和函数问题

时间:2015-03-12 01:26:35

标签: c++ c function parameters

#include <stdio.h>
#include <stdlib.h>

int main(int agrc, char* argv[])
{
    int num = atof(argv[1]);

    *par_ou_impar(num);

    return 0;
}

char *par_ou_impar(int aux)
{
    return (aux % 2 == 0) ? "par" : "impar";
}

我想创建一个程序来接收函数char *par_ou_impar中的参数int,如果它甚至返回"par",则返回"impar"

我不明白什么是错的,但它告诉我以下错误:

'par_ou_impar' : 'char *(int)' differs in levels of indirection from 'int ()' - 
                                          line 14 illegal indirection - line 8

3 个答案:

答案 0 :(得分:1)

首先,atof()const char*转换为double,而atoi()是相应的&#34; C&#34;用于转换为int的库函数。

另外,字符串文字像&#34; par&#34;和#34; impar&#34;应该返回const char* s而不是char* s - 覆盖其内容是不合法的,如果您隐式丢弃const,编译器会抱怨。 argv[]也可以是const

此外,如果某个功能至少在翻译单元中没有声明,则无法从main()调用该功能。因此,您必须将整个par_ou_impar(int)函数定义移到main()之上(最简单的方法),或者添加一个声明,如下所示....

#include <iostream>  // for cerr, cout
#include <cstdlib>   // for atoi

const char* par_ou_impar(int aux);  // declare here, define below

int main(int argc, const char* const argv[])
{
    if (argc < 2)
    {
        std::cerr << "usage: " << argv[0] << " <number>\n"
                     "reports whether <number> is even\n";
        return 1;
    }

    int num = std::atoi(argv[1]);

    std::cout << par_ou_impar(num) << '\n';

    // no need to return 0 - that's implicit in C++
}

const char* par_ou_impar(int aux)
{
    return (aux % 2 == 0) ? "par" : "impar";
}

值得注意的是atoi如果其参数(上面的argv[1])包含尾随的非数字字符,则不会报告错误:例如"123x"产生123并忽略x"-3/2"产生-3并忽略/2。可以按如下方式执行对法定号码的更有力的检查:

std::istringstream iss(argv[1]);
char c;
if (iss >> num && !(iss >> c))
   ... num was parsed successfully and no trailing non-whitespace ...
else
   ... report the error ...

如果您碰巧使用非标准&#34;提升&#34;库,boost::lexical_cast<int>(argv[1])是一种有时候方便的选择,但为单个错误检查设置try / catch有点冗长和笨拙:

try
{
    int num = boost::lexical_cast<int>(argv[1]);
    std::cout << par_ou_impar(num) << '\n';
}
catch (const std::exception& e)
{
    std::cerr << "parsing of number from argv[1] failed...\n";
    return 1;
}

答案 1 :(得分:0)

我不理解您的错误消息。这些是我需要进行的更改才能使其编译。您需要在调用之前声明函数原型。此外,您应该在C ++中使用const char *作为字符串文字。

#include <stdio.h>
#include <stdlib.h>

const char *par_ou_impar(int aux);

int main(int agrc, char* argv[])
{
    int num = atof(argv[1]);

    *par_ou_impar(num);

    return 0;
}

const char *par_ou_impar(int aux)
{
    return (aux % 2 == 0) ? "par" : "impar";
}

如果需要,您可以test代码。

答案 2 :(得分:0)

你错过了函数原型,当你在par_ou_impar()中调用main()时,编译器还不知道如何调用par_ou_impar()函数,所以你需要给出编译提示,你可以

  1. par_ou_impar()的定义之前移动main()的定义。
  2. 提供函数原型,即main()之前的函数声明,函数声明只是

    char *par_ou_impar(int number);
    
  3. 你的程序中有其他错误,但它们并没有阻止它编译。<​​/ p>

    我的建议是启用编译器警告,这样可以让您了解其他问题。