本文介绍了打印字符串有困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行程序时,第二个printf()打印string2,并将扫描到的string1中的任何内容附加到末尾.

When I run the program, the second printf() prints string2 with whatever was scanned into string1 attached to the end.

例如将123扫描到string1中,然后打印:Is before "12ab123".与12ab相对.

e.g. 123 was scanned into string1 then it prints: Is before "12ab123".as opposed to 12ab.

为什么不只是"12ab"?

char string1[MAX_STR_LEN];
char string2[4]={'1','2','a','b'};
char five='5';
char abc[3]={'a','b','c'};
printf("Enter a string:");
scanf("%s", string1);
printf("Is before \"%s\":",string2);

推荐答案

字符串是C中以null结尾的char数组.

A string is a null terminated char array in C.

更改

char string2[4]={'1','2','a','b'};

char string2[5]={'1','2','a','b', '\0'};

(与char string2[] = "12ab";相同)

这篇关于打印字符串有困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 13:12