【问题标题】:Trouble with argc and argvargc 和 argv 的问题
【发布时间】:2013-02-02 06:27:47
【问题描述】:

尝试向我的程序添加命令行参数。所以我在做实验,无法为我的一生找出这个智能警告。它一直说它期待一个')',但我不知道为什么。

这是它不喜欢的代码:

    // Calculate average
    average = sum / ( argc – 1 );   

然后它在减法运算符下划线。以下是完整的程序。

#include <iostream>

int main( int argc, char *argv[] )
{
    float average;
    int sum = 0;

    // Valid number of arguments?
    if ( argc > 1 ) 
    {
       // Loop through arguments ignoring the first which is
       // the name and path of this program
       for ( int i = 1; i < argc; i++ ) 
       {
           // Convert cString to int 
           sum += atoi( argv[i] );    
       }

       // Calculate average
       average = sum / ( argc – 1 );       
       std::cout << "\nSum: " << sum << '\n'
              << "Average: " << average << std::endl;
   }
   else
   {
   // If invalid number of arguments, display error message
       // and usage syntax
       std::cout << "Error: No arguments\n" 
         << "Syntax: command_line [space delimted numbers]" 
         << std::endl;
   }

return 0;

}

【问题讨论】:

  • 它可能会试图警告您,您可能期待的东西与您正在计算的东西不同。提示:sumargc 的类型是什么? :-)

标签: c++ argv argc


【解决方案1】:

我尝试在我的机器上使用 g++ 4.6.3 编译您的代码,但出现以下错误:

pedro@RovesTwo:~$ g++ teste.cpp -o  teste
teste.cpp:20:8: erro: stray ‘\342’ in program
teste.cpp:20:8: erro: stray ‘\200’ in program
teste.cpp:20:8: erro: stray ‘\223’ in program
teste.cpp: Na função ‘int main(int, char**)’:
teste.cpp:16:33: erro: ‘atoi’ was not declared in this scope
teste.cpp:20:35: erro: expected ‘)’ before numeric constant

看起来那行中有一些奇怪的字符。删除并重新编写修复错误的行。

【讨论】:

    【解决方案2】:

    你认为是减号的字符是别的东西,所以它不会被解析为减法运算符。

    你的版本:

    average = sum / ( argc – 1 ); 
    

    正确的版本(剪切并粘贴到您的代码中):

    average = sum / ( argc - 1 ); 
    

    请注意,使用整数计算平均值可能不是最好的方法。您在 RHS 上有整数运算,然后将其分配给 LHS 上的float。您应该使用浮点类型执行除法。示例:

    #include <iostream>
    
    int main()
    {
      std::cout << float((3)/5) << "\n"; // int division to FP: prints 0!
      std::cout << float(3)/5 << "\n";   // FP division: prints 0.6
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 2013-04-01
    • 2019-04-11
    • 2011-04-15
    • 2012-04-20
    • 1970-01-01
    • 2013-09-08
    • 2020-11-03
    相关资源
    最近更新 更多