0

我目前有一个 c++ Linux 程序,它从文件中读取参数“P”并将其加载到 RAM 中以进行进一步操作。该文件具有以下行:

P = 123

我希望程序从 shell 输入而不是文件中获取 P。我对所有选项持开放态度,只要我可以在 SSH 连接时手动输入 P。我想到的是输入提示:

sudo myprogram start
enter P value : (I would manually enter "123" here)

或者也许是一个论点:

sudo myprogram start 123

做起来一定很简单,但我不知道怎么做,所以非常感谢任何帮助!

4

4 回答 4

1

如果这是文件具有的唯一数据,则文件操作是不必要的。只需将 123(或其他)传递给您的 C++ 程序并将字符串转换为整数。

假设您将整数作为第二个参数传递,那么:

int  p = atoi(argv[2]);

更好的选择是使用 strtol:

char *s, *ptr;

s = argv[1];
int p = strtol(s, &ptr, 10);

如果您无法更改 C++ 代码,那么只需执行以下操作:

echo "P = 123" > file && myprogram start 

如果您的文件有更多内容并且您不能简单地显,请将现有行替换为新值:

 sed -i "s/P = [0-9]*/P = 123/" file && myprogram start
于 2012-10-29T13:37:40.393 回答
0

第一个版本(从键盘输入):

echo -n "enter P value: "
read P

第二个版本(作为 shell 脚本参数传递):

P=$1

第三版(学习 bash/shell 编程):

于 2012-10-29T13:33:44.610 回答
0

这是基本的 C++。查看下面的示例代码或访问我从中复制它的站点。

#include <iostream>

// When passing char arrays as parameters they must be pointers
int main(int argc, char* argv[]) {
    if (argc < 5) { // Check the value of argc. If not enough parameters have been passed, inform user and exit.
        std::cout << "Usage is -in <infile> -out <outdir>\n"; // Inform the user of how to use the program
        std::cin.get();
        exit(0);
    } else { // if we got enough parameters...
        char* myFile, myPath, myOutPath;
        std::cout << argv[0];
        for (int i = 1; i < argc; i++) { /* We will iterate over argv[] to get the parameters stored inside.
                                          * Note that we're starting on 1 because we don't need to know the 
                                          * path of the program, which is stored in argv[0] */
            if (i + 1 != argc) // Check that we haven't finished parsing already
                if (argv[i] == "-f") {
                    // We know the next argument *should* be the filename:
                    myFile = argv[i + 1];
                } else if (argv[i] == "-p") {
                    myPath = argv[i + 1];
                } else if (argv[i] == "-o") {
                    myOutPath = argv[i + 1];
                } else {
                    std::cout << "Not enough or invalid arguments, please try again.\n";
                    Sleep(2000); 
                    exit(0);
            }
            std::cout << argv[i] << " ";
        }
        //... some more code
        std::cin.get();
        return 0;
    }
}
于 2012-10-29T13:36:33.750 回答
0

您不只是想在您的 C++ 程序中被提示输入值吗?如果这是您想要的,这个简单的代码将完成这项工作:

#include <iostream>
int main(int argc, char **argv) {
  int p = 0;
  std::cout << "Enter P value: ";
  std::cin >> p;
  std::cout << "Entered value: " << p << std::endl;
  return 0;
}
于 2012-10-29T13:49:12.283 回答