c - 为什么第一个字母后面有一个空格?

标签 c file printf space

我有这个代码:

void text(){    
    FILE *fp;
    fp = fopen( "Text.txt", "w" );
    if (fp == NULL)printf("not open\n");
    char txt[100];
    char c;
while(1){   
    char c = getche();
    if (c == '\e')
        break;
    txt[0] = c;
    gets(txt+1);
    fprintf(fp, "%s ",txt);
}
    fclose(fp);
}

它工作正常,输出如下:Hello there.

void text(){    
    char fname[20] ; 
    puts("Write file name");
    scanf("%s",&fname); //input of the file name
    char ext[5] = ".txt";
    char fileSpec[strlen(fname)+strlen(ext)+1]; //file name assambly
    snprintf( fileSpec, sizeof( fileSpec ), "%s%s", fname, ext);
    FILE *fp;
    fp = fopen( fileSpec, "w" );
    if (fp == NULL)printf("not open\n");
    char txt[100];
    char c;
while(1){   
    char c = getche();
    if (c == '\e')
        break;
    txt[0] = c;
    gets(txt+1);
    fprintf(fp, "%s ",txt);
}
    fclose(fp);
}

我从网站上获取了上半部分,单独测试它并且它有效。下半部分是相同的,当我将两者放在一起时,输出将如下所示:你好。

为什么会有那个空间?

最佳答案

您没有提供足够的上下文(即标准输入中放入了什么?文件中有什么?)。

但是您的 fprintf(fp, "%s ",txt); 中有一个空格,这似乎是罪魁祸首。 (请注意,while 循环可以运行多次,从而在输出到文件的内容之间添加空格)。

关于c - 为什么第一个字母后面有一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33588399/

相关文章:

c - 在 C 中使用 printf_P 右对齐

debugging - WWW::Mechanize::Firefox:调试尝试在未打开的文件句柄上停止打印()

c - 如何避免 if else 的多重链

c - 如何在 Xcode 中为命令行工具程序创建 .app 文件

c - 在 C 中定义自定义命令行参数?

file - V在Coq文件扩展名中代表什么?

无法正确对齐 printf 代码

c - 在使用 GDI 的基于 C 的遗留 win32 系统中使用 GDI+

python - 使用文件作为计数函数的参数,为文本文件中的每个字母创建计数

regex - 在 bash 中检查文件的正则表达式