我在C++中有一种计算器,它应该在执行时接受参数.但是,当我输入7作为参数时,当放入变量时它可能会变成10354.这是我的代码:
#include "stdafx.h"
#include <iostream>
int main(int argc, int argv[])
{
using namespace std;
int a;
int b;
if(argc==3){
a=argv[1];
b=argv[2];
}
else{
cout << "Please enter a number:";
cin >> a;
cout << "Please enter another number:";
cin >> b;
}
cout << "Addition:" << a+b << endl;
cout << "Subtaction:" << a-b << endl;
cout << "Multiplycation:" << a*b << endl;
cout << "Division:" << static_cast<long double>(a)/b << endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*igt 20
你到哪里去了int argv[]?第二个论点main是char* argv[].
您可以使用strtol或使用浮点数将这些命令行参数从字符串转换为整数strtod.
例如:
a=strtol(argv[1], nullptr, 0);
b=strtol(argv[2], nullptr, 0);
Run Code Online (Sandbox Code Playgroud)
但是你不能只改变参数类型,因为无论你喜不喜欢,操作系统都会以字符串形式给你命令行参数.
注意:您必须#include <stdlib.h>(或#include <cstdlib>和using std::strtol;)使用该strtol功能.
如果要进行错误检查,请使用strtol而不是atoi.使用它几乎一样容易,它还为您提供指向字符串中解析终止的位置的指针.如果指向终止NUL,则解析成功.当然,验证argc确保用户提供足够的参数并避免尝试从中读取缺少的参数是很好的argv.
错误检查示例:
char* endp;
a = strtol(argv[1], &endp, 0);
if (endp == argv[1] || *endp) { /* failed, handle error */ }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20769 次 |
| 最近记录: |