我是C的新手.我正在使用命令行编写一个简单的计算器.命令行应具有以下格式:
programname firstNumber运算符secondNumber
这是我到目前为止所得到的:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] << endl;
exit(0);
}
else
{
int firstNumber = atoi(argv[1]);
char theOperator = atoi(argv[2]);
int secondNumber = atoi(argv[3]);
switch (theOperator)
{
case'+':
{
cout << "The answer is " << firstNumber + secondNumber << endl;
break;
}
case '-':
{
cout << "The answer is " << firstNumber - secondNumber << endl;
break;
}
case '*':
{
cout << "The answer is " << firstNumber * secondNumber << endl;
break;
}
case '/':
{
if (secondNumber == 0)
{
cout << "Can not devide by a ZERO" << endl;
break;
}
else
{
cout << "The answer is " << firstNumber / secondNumber << endl;
break;
}
}
}
}
}
该程序无法运行.当我运行它时,它会显示一个适当的用法消息并结束程序.谁能帮帮我吗?
解决方法:
其他人已经给你答案,但你可以很容易地自己想出这个.只需在您知道代码进入的位置打印argc:
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "argc is: " << argc << endl; // Debug output that you delete later
cerr << "Usage: " << argv[0] << endl;
exit(0);
}
else
然后回过头来看看argc.当你发现argc实际上是4并且你想知道argc里面是什么时你应该写一些代码来打印它,这样你就可以搞清楚……就像这样:
int main(int argc, char* argv[])
{
cout << "argc is: " << argc << endl; // Debug output that you delete later
for (int i = 0; i < argc; ++i)
{
// Print out all of the arguments since it's not working as you expect...
cout << "argv[" << i << "] = " << argv[i] << endl;
}
if (argc != 3)
{
cerr << "Usage: " << argv[0] << endl;
exit(0);
}
else
而你很快就会弄清楚出了什么问题……
请学习如何做到这一点,因为它会保存你的,但将来你不必在这里等待答案.
此外,您的代码中还有另一个错误.
为什么你要将字符从字符串转换为int?
else
{
int firstNumber = atoi(argv[1]);
char theOperator = atoi(argv[2]); // <<< WTF? Why?
int secondNumber = atoi(argv[3]);
switch (theOperator)
你可能想摆脱那里的atoi
部分,然后去:
char theOperator = argv[2][0]; // First character of the string
假设第二个参数将始终只有一个字母…您可能希望强制执行/检查.请参阅strlen()和std::string并注意argv [2]的类型是char *(指向char的指针).
我还建议您阅读从SO Howto-Ask Help Page链接的How to debug small programs.这可能会有所帮助.不,我认为你的问题不好.调试小程序是您将来需要的一项技能,如果您打算编程,那么现在就可以从中受益.
欢迎编程和C