我需要将cin转换为argc argv输入样式,并且不知道如何处理。这是我代码的主体,如果可以得到帮助,所有输入都将放在这里。所有这些都在c ++中
[有人告诉我,“您需要在主要功能中使用argc和agrv []。因此,用户在运行程序时可以将信息输入到程序中。例如,” yourprogram.exe -P 50“。预先谢谢你。
int main(int argc, char* argv[])
{
string userChoice = "";
using std::string;
int stop = 0;
double pwm = 0;
WritePWMfreq(46);
cout << "PWM frequency set to: " << ReadPWMfreq() + 1 << "Hz" << endl;
cout << "Enter 'P' to set the Duty Cycle for the PWM, 'A' to see the Analogue Port number \nor 'L' to set a target value for ADC0 port to match: " << endl;
cin >> userChoice;
int userPWM = 0;
if (userChoice == "P" | userChoice == "p")
{
cout << "Please enter a duty cycle value between 1 and 100: " << endl;
cin >> userPWM;
if ((userPWM < 1) | (userPWM > 100))
{
cout << "That is outside of the possible range. Please try again. " << endl;
return 0;
}
else
WritePWM(userPWM);
ReadPWM();
return 0;
}
if (userChoice == "A" | userChoice == "a")
{
int userPort = 0;
cout << "Please choose a port between 0 to 7 to find its value: " << endl;
cin >> userPort;
if ((userPort < 0) | (userPort > 7))
{
cout << "There is no port of this number. Please try again. " << endl;
return 0;
}
else
WriteADCPort(userPort);
return 0;
}
if ((userChoice == "L") | (userChoice == "l"))
{
int i = 50;
int userTarget = 0;
cout << "Please enter a target value: " << endl;
cin >> userTarget;
cout << "The target value is: " << userTarget << endl;
WritePWM(i);
ReadPWM();
ReadADCPort();
if ((i <= 100) | (i >= 0) | (stop = 1))
{
while (ReadADCPort() <= userTarget)
{
WritePWM(i--);
ReadPWM();
ReadADCPort();
pwm = ReadPWM();
if (pwm == 1 | pwm == 0)
{
stop = 1;
}
}
while (ReadADCPort() >= userTarget)
{
WritePWM(i++);
ReadPWM();
ReadADCPort();
pwm = ReadPWM();
if (pwm == 1 | pwm == 0)
{
stop = 1;
}
}
}
}
else
cout << "Invalid option. Please enter either 'A', 'P' or 'L'. " << endl;
return 0;
}
该程序必须能够由自动测试仪运行,因此需要能够在命令行中运行。不知道如何启动或如何使用argv argc输入
argv
只是一个数组,因此请转换数组中相应插槽的值。第一个命令行选项位于argv[1]
中,第二个命令行选项位于argv[2]
中,stoi
可用于将字符串转换为整数。
userChoice = argv[1];
userPWM = stoi(argv[2]);
userPort = stoi(argv[2]);
userTarget = stoi(argv[2]);
此代码中的错误检查为零。您至少应检查用户是否输入了两个值
if (argc < 3)
cout << "No option specified" << endl;