argc和argv出现故障
Trouble with argc and argv
我正在尝试将命令行参数添加到程序中。所以我一直在做实验,无法理解这种对我生命的智能感知警告。它一直说它在期待一个")",但我不知道为什么。
这是它不喜欢的代码:
// 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 the 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 an invalid number of arguments, display an error message
// and usage syntax
std::cout << "Error: No argumentsn"
<< "Syntax: command_line [space-delimited numbers]"
<< std::endl;
}
return 0;
}
您认为是减号的字符是其他字符,因此不会将其解析为减法运算符。
您的版本:
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
}
我试图用g++4.6.3在我的机器上编译你的代码,但得到了以下错误:
cd ~
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
看起来这行有一些奇怪的字符。删除并重新写入行修复了错误。
相关文章:
- 分段故障(堆芯转储)矢量
- C++中的动态铸造故障
- 数组的指针从不分段故障
- 为什么我的for循环不能正确获取argv
- vscode g++链路故障:体系结构x86_64的未定义符号
- 访问被拒绝后,c++中的故障保护代码
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 调试 CUDA MMU 故障
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- 碱基对映射 - 将 argv[i] 移动到整数或字符作为输入
- 如何将 argv[1] 转换为 LPCVOID?
- Arch Linux.AUR 包 mysql 不能用 makepkg 构建.错误:构建 () 中出现故障
- 正在处理故障(堆芯转储)
- 在 Boost::fiber 中引发的BOOST_ASSERT故障 Visual Studio "Debug" 构建
- 如何进行故障排除:未定义对"非虚拟 thunk to ..."的引用
- C++函数过载会导致 SEG 故障
- 分段故障 运行C++代码时出现 SIGSEGV
- C ++编译器如何获取argv字符串的长度
- 当新的故障时,是否有必要留出一些紧急内存?
- argc和argv出现故障