有没有一种方法可以初始化一个空字符串数组,然后请求用户输入,该输入将保存到字符串数组中,如果输入较小,则保留空的前导空格。 我计划使用更长的字符串数组和附加空格,以便我可以进行就地字符替换。 例如:
char foo[25];
scanf(%s,foo);
foo = this is a test"
print foo;
结果如下:
"this is a test "
最佳答案
您的问题不一致,您询问前导空格,但您的示例显示尾随空格。如果你的意思是尾随空白,你可以这样做:
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 25
int main() {
char string[BUFFER_SIZE];
memset(string, ' ', BUFFER_SIZE - 1); // initialize with spaces
string[BUFFER_SIZE - 1] = '\0'; // terminate properly
if (fgets(string, BUFFER_SIZE, stdin) != NULL) {
size_t length = strlen(string);
string[length - 1] = ' '; // replace the newline \n
if (length < BUFFER_SIZE - 1) {
string[length] = ' '; // replace extra '\0' as needed
}
printf("'%s'\n", string); // extra single quotes to visualize length
}
return 0;
}
使用
> ./a.out
this is a test
'this is a test '
>
添加单引号只是为了让您实际上可以看到空格被保留。 @BLUEPIXY 的方法非常有意义,只不过它会在您特别询问保留现有空格的输入中附加新的空格。
如果您想保留前导空格,也可以这样做。
关于创建带有前导空格的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553120/