简体   繁体   English

argc和argv遇到问题

[英]Trouble with argc and argv

Trying to add command line arguments to my programs. 尝试向我的程序添加命令行参数。 So I was experimenting and cannot figure out this intellisense warning for the life of me. 因此,我正在尝试,无法弄清这个智能警告对我的一生。 It keeps on saying it is expecting a ')', but I have no idea why. 它一直在说它期待一个')',但我不知道为什么。

Here is the code it does not like: 这是它不喜欢的代码:

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

Then it underlines the subtraction operator. 然后,它强调了减法运算符。 Below is the full program. 以下是完整程序。

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

} }

The character you think is a minus sign is something else, so it is not parsed as a subtraction operator. 您认为是减号的字符是其他字符,因此不会将其解析为减法运算符。

Your version: 您的版本:

average = sum / ( argc – 1 ); 

Correct version (cut and paste into your code): 正确的版本(剪切并粘贴到您的代码中):

average = sum / ( argc - 1 ); 

Note that calculating an average using integers might not be the best way to do it. 请注意,使用整数计算平均值可能不是最佳方法。 You have integer arithmetic on the RHS, which you then assign to float on the LHS. 您在RHS上具有整数算术,然后将其分配给LHS上的float You should perform the division using floating point types. 您应该使用浮点类型执行除法。 Example: 例:

#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
}

I tried to compile your code on my machine with g++ 4.6.3 and got the follow error: 我尝试使用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

Looks like there is some strange char in that line. 看起来该行中有一些奇怪的字符。 Remove and re-write the line fixed the error. 删除并重新写入修正错误的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM