麻烦与argc和argv

时间:2013-02-17 20:48:14

标签: c++ argv argc

尝试向我的程序添加命令行参数。所以我正在进行实验,无法弄清楚这对我生命的智能警告。它继续说它期待')',但我不知道为什么。

以下是它不喜欢的代码:

    // 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;

}

2 个答案:

答案 0 :(得分:9)

您认为减号的字符是其他字符,因此不会将其解析为减法运算符。

您的版本:

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
}

答案 1 :(得分:2)

我尝试使用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

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

相关问题