“%s”,字符串不在字符串后打印空格
在此代码段中:
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不能用于字符串格式吗? 可能会发生什么其他想法?
strcat
不支持格式化字符串,它只是连接。 此外,使用额外的括号对会导致C编译器将其解析为逗号运算符 ,而不是作为传递给函数的参数。
也就是说, strcat((char*)cmdargs, ("%s ", tokens[i]));
将导致调用strcat((char*)cmdargs, tokens[i]);
由于逗号运算符调用所有表达式的副作用,但返回最后一个值。
如果你想使用strcat
,你应该写:
strcat((char*)cmdargs, " "); strcat((char*)cmdargs, tokens[i]);
同样的事情也适用于strcpy
函数调用。
编写自己的格式化字符串连接函数版本,如果这是你想要的:
(另)
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]); ...