【问题标题】:Using loop variable in string for call to system() in C在字符串中使用循环变量来调用 C 中的 system()
【发布时间】:2013-10-09 13:19:20
【问题描述】:

初学者的问题-如何在命令字符串中使用k?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int k;
    for(k = 0; k < 5; k++)
    {
       // make k appear in place of USE_K_HERE
       char argv[] = "./a.out -k USE_K_HERE < test.txt";
       system(argv);
    }
}

【问题讨论】:

  • 仅供参考,您将“-k ”放在错误的位置。 shell 将尝试将“-k”和“”解释为与 test.txt 相同的文件名。 -k 是您的 a.out 程序的一个选项吗?如果是这样,它必须出现在
  • 请不要使用void main()。 Main 应该返回 int。使用int main(void)int main(int c, char **v)
  • @koodawg 是的,它是 ./a.out 的参数。我会改变的。
  • @wildplasser 我会改成 int main()

标签: c string loops


【解决方案1】:

你可以在循环体中使用snprintf:

char cmd[100];
snprintf( cmd, sizeof(cmd), "./a.out -k %d < test.txt", k );
system(cmd);

http://en.cppreference.com/w/cpp/io/c/fprintf

【讨论】:

  • 除了 a.out 的选项必须出现在
  • snprintf(cmd, sizeof(cmd), "./a.out -k %d
  • @koodawg:固定问题和答案。
【解决方案2】:

您可以使用非标准的itoa(整数到alpha)或使用更受欢迎的sprintf

char argv[64]; // for example
sprintf(argv, "./a.out -k %d < test.txt", k);

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多