3

所以这是我的原始代码:

#include <iostream>

using namespace std;

int main ()
{
    float x;  
    cout << "Please enter an integer value: ";
    cin >> x;

    if ((x >= 100) && (x < 200)) {
        cout << "split";
    } else if (x == 0 ||x == 1 ) {
        cout << "steal";
    } else {
        cout << "split";
    } 

    system("pause");
}

它工作得很好,但我需要它以这种方式运行:

C:\> program.exe 109

它将读取109并给出输出 - "steal"

C:\> program.exe 0.5

它会读取0.5并给我输出"split"

我必须在原始代码中添加什么才能做到这一点?

4

3 回答 3

5

将您的主要更改为

int main (int argc, char** argv)

您可以检查程序中指定参数的数量argc以及 中的值(如char *argv。您可以使用将该值转换为浮点数std::stof

float x = 0.0f;
if (argc > 1) {
    x = std::stof(argv[1]);
} else {
    std::cerr << "Not enough arguments\n";
    return 1;
}

请注意,程序的第一个参数是可执行文件本身的名称(program.exe在您的情况下),因此您需要检查至少两个参数。

参考资料:http ://en.cppreference.com/w/cpp/string/basic_string/stof

于 2012-12-18T06:29:18.937 回答
0

Can we have more clarity on the question? Do you want to know how to execute the code using command line arguments? In that case here it is:

int main (int no_of_args, char* arglist[])
{
}

In argList, the first item holds the name of the executable and subsequent items hold the inputs provided.

于 2012-12-18T06:32:32.420 回答
0

您可以通过使用命令行参数来做到这一点。这是主要功能的格式:

int main (int argc, _TCHAR* argv[])
{
}

这里argc表示参数的数量(在您的情况下返回 2, program.exe 0.5 )

argv代表两个字符串。第一个包含program.exe和第二个包含0.5

这样你就可以解决你的问题

于 2012-12-18T06:31:31.783 回答