使用Scanf输入字符指针数组,但是当我在“空格”被截断后输入字符串时

问题描述 投票:0回答:1

我想在运行这些代码段时输入字符指针数组,在运行这些代码段时将输入字符串“空格”后的其余字符串截断:

enter image description here

我要打印整个输入字符串

代码是:

#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;
}
c string char scanf
1个回答
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)中:

    '%'之前的空格允许在行的开头绕过空格(在术语上,也就是制表符,换行符等)
  • ''11'将保存在
  • str中的字符限制为11个字符,而没有计算同样放置在str中的最终空字符,否则长于11个字符的输入将写出数组]
  • [^\n]允许读取到行尾(不保存换行符),假设它不太长,则字符串内部的空格不视为分隔符,因为%s就是这种情况。>
© www.soinside.com 2019 - 2024. All rights reserved.