我想在运行这些代码段时输入字符指针数组,在运行这些代码段时将输入字符串“空格”后的其余字符串截断:
我要打印整个输入字符串
代码是:
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str = malloc(sizeof(char)*4);
printf("Enter The String: ");
scanf("%s", str);
printf("The String is: %s\n", str);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str = malloc(12);
printf("Enter The String: ");
if (scanf(" %11[^\n]", str) == 1)
printf("The String is: %s\n", str);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall c.c pi@raspberrypi:/tmp $ ./a.out Enter The String: Hello World The String is: Hello World pi@raspberrypi:/tmp $ ./a.out Enter The String: Hello World! The String is: Hello World pi@raspberrypi:/tmp $ ./a.out < /dev/null Enter The String: pi@raspberrypi:/tmp $
在scanf(" %11[^\n]", str)
中:
[^\n]
允许读取到行尾(不保存换行符),假设它不太长,则字符串内部的空格不视为分隔符,因为%s
就是这种情况。>