我正在尝试使用以下代码在字符串末尾添加一些字符。我没有得到所需的输出。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int l,i;
char a[30];
printf("Enter \n");
scanf("%s",a);
l=strlen(a);
for(i=l;i<(29-l);i++)
{
scanf("%c",&a[i]);
a[i+1]='\0';
printf("\n%s",a);
}
return 0;
}
最佳答案
我猜,问题出在空格上。输入第一个字符串后,输入缓冲区中仍然有换行符 \n
。当您用 scanf
读取一个字符时,您得到的是换行符,而不是您输入的字符。
当您在格式字符串前添加空格时,可以跳过空格
scanf(" %c",&a[i]);
现在它将附加在字符串末尾输入的字符。
更新:
来自scanf
The format string consists of a sequence of directives which describe how to process the sequence of input characters.
...
• A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
这意味着,当您在格式字符串中插入空格时,它将跳过输入中的所有空格。
对于其他输入指令(例如 %s
或 %d
),这会自动发生。但是 %c
接受下一个字符,即使它是空白字符。因此,如果您想在这种情况下跳过空格,则必须通过在格式字符串中插入空格来告诉 scanf
。
关于c - 在字符串末尾添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23055531/