【问题标题】:Sprintf with pointers, constants and string formatting带有指针、常量和字符串格式的 Sprintf
【发布时间】:2016-04-10 00:32:24
【问题描述】:

我是 C 的新手,我在简化这个程序时遇到了麻烦。我正在尝试将name oncestrcat name 初始化为command once。它是一个命令行可执行文件,带有两个参数和一个可选参数,用于文件名“new py”或“new txt”或“new py script”。我运行 Windows 的 MinGW 进行编译。

有没有一种类型可以用一行存储 argv 值和字符串常量?

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

int main(int argc, char *argv[]) {
    char command[100] = "cd . > ";
    char *type = argv[1];
    char * name;
    strcat(command,"\"");
    if (argc == 3) {
        char * name = argv[2];
        //strcat(command,name);
    } else {
        char name[20];
        sprintf(name,"new %s file",type);
        //strcat(command,str);
    }
    strcat(command,name);
    strcat(command,".");
    strcat(command,type);
    strcat(command,"\"");
    system(command);
    return 0;
}

【问题讨论】:

  • char * name = argv[2];char name[20]; 在 if-else 块的本地范围内。修复示例:char name[20]; if(argc == 3){ strcpy(name, argv[2]); } else { sprintf(name,"new %s file",type); } strcat(command, name);
  • 谢谢。现在已经修好了。你认为我可以sprintf 命令的其余部分而不是 strcats 吗?
  • 你最喜欢的。

标签: c pointers printf argv argc


【解决方案1】:

正如BLUEPIXY 所述,我的块需要包含“char name[20]; if(argc == 3){ strcpy(name, argv[2]); } else { sprintf(name,"new %s file",type); } strcat(command, name);”。在这些更改之后,我将所有strcats 转换为一个 sprinf

我之前对存储 argv 项目的理解是编译需要 char 指针,因为不会定义 args。由于name的初始化,它们不再需要了。

我现在精简的代码是这样的:

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

int main(int argc, char *argv[]) {
    char command[100];
    char * type = argv[1];
    char name[50];
    if (argc == 3) {
        strcpy(name, argv[2]);
    } else {
        sprintf(name,"new %s file",type);
    }
    sprintf(command,"cd . > \"%s.%s\"",name,type);
    system(command);
    return 0;
}

再次感谢 BLUEPIXY 消除我的误解。

【讨论】:

  • 请注意,如果nametype 包含",则可能会发生可怕的事情。确保这些内容仅来自完全受信任且了解此计划限制的来源。
  • 注意:为了增强理智,请使用snprintf()
猜你喜欢
  • 2020-03-25
  • 2013-11-10
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
相关资源
最近更新 更多