【问题标题】:"%s ", string not printing space after string“%s”,字符串后面没有打印空格
【发布时间】:2013-09-19 12:34:11
【问题描述】:

在此代码中 sn-p:

printf("shell> ");
fgets(input, MAX_INPUT_SIZE, stdin);

//tokenize input string, put each token into an array
char *space;
space = strtok(input, " ");
tokens[0] = space;

int i = 1;
while (space != NULL) {
  space = strtok(NULL, " ");
  tokens[i] = space;
  ++i;
}

//copy tokens after first one into string
strcpy((char*)cmdargs, ("%s ",tokens[1]));
for (i = 2; tokens[i] != NULL; i++) {
  strcat((char*)cmdargs, ("%s ", tokens[i]));
}

printf((char*)cmdargs);

输入:echo hello world and stuff,程序打印:

helloworldandstuff

在我看来,strcat((char*)cmdargs, ("%s ", tokens[i])); 行应该将 tokens[i] 处的字符串与后面的空格连接起来。 strcat 不适用于字符串格式吗?任何其他想法可能会发生什么?

【问题讨论】:

  • 是的,它编译在这里就好了。关于printf((char*)cmdargs); 声明的一个警告,仅此而已。该语句仅用于调试目的。
  • 它会编译因为逗号运算符,而只是"%s ", tokens[i] 不像你想的那样有效

标签: c string strcat


【解决方案1】:

strcat 不支持格式化字符串,它只是进行连接。此外,您使用额外的一对括号会导致 C 编译器将其解析为 comma operator,而不是作为传递给函数的参数。

也就是说,strcat((char*)cmdargs, ("%s ", tokens[i])); 将导致调用 strcat((char*)cmdargs, tokens[i]);,因为逗号运算符调用所有表达式的副作用,但返回最后一个值。

如果你想使用strcat,你应该写:

strcat((char*)cmdargs, " ");
strcat((char*)cmdargs, tokens[i]);

同样的事情也适用于strcpy 函数调用。

【讨论】:

    【解决方案2】:

    编写您自己的格式化字符串连接函数版本,如果这是您想要的:

    (未经测试)

    int strcatf(char *buffer, const char *fmt, ...) {
        int retval = 0;
        char message[4096];
        va_list va;
        va_start(va, fmt);
        retval = vsnprintf(message, sizeof(message), fmt, va);
        va_end(va);
        strcat(buffer, message);
        return retval;
    }
    
    
    ...
    strcatf((char*)cmdargs, "%s ", tokens[i]);
    ...
    

    【讨论】:

    • 真的很有趣!!但是我们需要 () 来调用吗?
    • 您想删除strcatf 调用中的额外括号,否则您会遇到与逗号运算符相同的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2022-10-02
    相关资源
    最近更新 更多