【发布时间】:2020-08-06 09:33:47
【问题描述】:
我需要将 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 输入
【问题讨论】:
-
这在大多数关于 C++ 的介绍性材料中都有介绍。
main()接受两个参数,一个int命名(按照约定)argc(参数计数)和一个char **命名为argv。argv代表一个字符串数组,argv[argc]是一个空指针。因此,更改main()以接受这些参数,然后根据需要迭代并检查/解释每个字符串。