"%S&QUOT ;,字符串不打印字符串后面空间 [英] "%s ", string not printing space after string

查看:149
本文介绍了"%S&QUOT ;,字符串不打印字符串后面空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此code片段在这里:

In this code snippet here:

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);

通过输入:回声你好世界和东西,该程序打印:

With the input: echo hello world and stuff, the program prints:

helloworldandstuff

在我看来,该行 strcat的((字符*)cmdargs,(%S,代币[I])); 应串联在令牌字符串[I]与下述它的空间。难道strcat的不是字符串格式化工作?任何其他的想法可能什么呢?

It seems to me that the line strcat((char*)cmdargs, ("%s ", tokens[i])); should concatenate the string at tokens[i] with a space following it. Does strcat not work with string formatting? Any other ideas what might be going on?

推荐答案

strcat的不支持格式化字符串,它只是做串联。此外,您的额外对括号的使用会导致C编译器来解析这个作为逗号操作符,而不是作为参数传递给函数。

strcat does not support formatting strings, it just does concatenation. Moreover, your use of the extra pair of parenthesis cause the C compiler to parse this as a comma operator, and not as arguments passed to the function.

这就是 strcat的((字符*)cmdargs,(%S,代币[I])); 将导致通话 strcat的((字符*)cmdargs,代币[I]); 为所有前pression的逗号操作符调用的副作用,但返回的最后一个值

That is, strcat((char*)cmdargs, ("%s ", tokens[i])); will result in a call strcat((char*)cmdargs, tokens[i]); as the comma operator invoke side-effect of all expression, but return the last value.

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

If you want to use strcat, you should write:

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

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

这篇关于"%S&QUOT ;,字符串不打印字符串后面空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆