繁体   English   中英

fgets 获取并初始化字符【】

[英]fgets gets and initialize char【】

问题是每行输入一个字符串(每个<10)可能包含空格,并将第二个字符串的前n 个字符放在第一个字符串的后面。 我尝试了很多次使用不同的输入功能,它们之间存在差异。 我想知道为什么 ? 像这样输入:

hello
c world
3

通缉: helloc w

#include<string.h>
void fun(char *s1, char *s2, int n) {
    int l = strlen(s1);
    for(int i=0;i<n;i++) {
        s1[l+i]=s2[i];
    }
    int m=strlen(s1);
    s1[m]='\0'; //It doesnot work.Because when it is not here the outcome is the same.Both `fgets` and `gets` 
}
int main()
{   char s1[10];char s2[8]; int n;
    gets(s1);
    gets(s2);
    scanf("%d",&n);
    fun(s1,s2,n);
    printf("%s",s1);
    return 0; //This is the only one output right.
}

但是如果

char s2[10];//output is :helloc w?@   What is different,why the length of string influence the output.

如果

char s2[8];
fgets(s1,10,stdin);
fgets(s2,8,stdin);
//output:
hello
c w

why fgets influence the format of output

你应该写在: fun(...)

int m = n + l;

代替:

int m = strlen(s1);

这是一个错误,因为strlen需要一个以空字符结尾的字符串,但空字符已被另一个字符覆盖。 因此,字符串不再以空值结尾。 新的空终止符只会写在下一行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM