lark 发表于 2015-6-29 12:56:45

如题:puts(),'\0' 打印输出

本帖最后由 lark 于 2015-6-29 12:56 编辑

这里有两个代码
问题是:这两个代码,代码1,直接输出,在没加'\0'的情况下,会继续输出乱码;代码2,以函数调用的方式,不管有没有加'\0',都不会输出乱码;
           所以,我想问:这是 编译自动处理 的结果 还是 函数调用 的亦或 是其他 或 C的原因?
/*这个代码数组都没有初始化;
*编译器:C-Free 5.0(未注册版);
*/


插入代码1:
(说明下:)
#include <stdio.h>
#include <conio.h>
int main(void){
        FILE *fp=fopen("F:\\MYTXT.TXT","w+");
    int i;
    char string;
    for(i=0;i<10;i++)
      string='a';
    puts(string);
    fputs(string,fp);
    fclose(fp);
    getch();
    return 0;
}

插入代码2:
#include <stdio.h>
#include <conio.h>
/*语言:C 语言;
* Novice need to pay attention(初学者要注意;
*/
void NOT_0        (void);        //不加'\0'的输出;
void HAVE_0 (void); //加'\0'的输出;

void NOT_0        (void){
        FILE *fp=fopen("F:\\NOT_0.txt","w+");
    int i;
    char string;
    for(i=0;i<10;i++)
      string='a';
                fputs(string,fp);
      fclose(fp);
    puts(string);   
}

/*从此例中可看到puts输出字符串时要遇到'\0’也就是字符结束符才停止,
*如上面的程序加上一句 string='\0';
*/

void HAVE_0 (void){
        FILE *fp=fopen("F:\\HAVE_0.txt","w+");
    int i;
    char string;
    for(i=0;i<10;i++)
      string='a';
    string='\0';
    puts(string);
        fputs(string,fp);
        fclose(fp);
    getch();
}


int main(void){
        NOT_0();
        HAVE_0();
        //在此注意调用NOT_0()和HAVE_0()的区别;
        return 0;
}


图片:

ryxcaixia 发表于 2015-6-29 12:56:46

本帖最后由 ryxcaixia 于 2015-6-30 09:06 编辑

附上MSDN对于两个函数的简单概述, 摘要如下
fputs:
Each of these functions copies string to the output stream at the current position. fputws copies the wide-character argument string to stream as a multibyte-character string or a wide-character string according to whether stream is opened in text mode or binary mode, respectively. Neither function copies the terminating null character.

puts:
The puts function writes string to the standard output stream stdout, replacing the string’s terminating null character ('\0') with a newline character ('\n') in the output stream

简单来说 puts会自定替换第一个\0字符为一个换行符('\n')
fputs写入标准流时, 不会将'\0'字符一并写入(这是肯定的 影响美观)

但两者都不会对字符串作一个加上'\0'的操作
即原来的字符串长什么样子 就输出什么样子
原来的是乱码 就输出乱码

哥斯拉不说话 发表于 2015-6-29 17:05:39

表示只要不加 '\0' 都会乱码,因为字符串要以 '\0' 结尾,没有的话用字符串函数puts,fputs就会乱码

ryxcaixia 发表于 2015-6-30 08:58:47

楼主 我表示我这边输出的 NOT_0 也是乱码 并且 这应该是理想的结果
因为及时在NOT_0内也是一堆乱码
楼主可以调试跟踪下程序 看看是不是编译器自动进行了栈内存清零操作


lark 发表于 2015-7-2 17:19:02

ryxcaixia 发表于 2015-6-30 08:58
楼主 我表示我这边输出的 NOT_0 也是乱码 并且 这应该是理想的结果
因为及时在NOT_0内也是一堆乱码
楼 ...

嗯,谢谢了

lark 发表于 2015-7-2 17:21:47

哥斯拉不说话 发表于 2015-6-29 17:05
表示只要不加 '\0' 都会乱码,因为字符串要以 '\0' 结尾,没有的话用字符串函数puts,fputs就会乱码

:lol:这个感觉看编译器了,就像有些编译器会自动加 “任意键结束一样”,而有些则不会
页: [1]
查看完整版本: 如题:puts(),'\0' 打印输出