#include <stdio.h> main(){
char *one="assssss"; char *two="assssss"; printf("please input two words:\n"); scanf("%s,%s",one,two);
printf("%s,%s\n",one,two); }
怎么每次输出都会比输入多几个莫名其妙的字符
#include <stdio.h> main(){
char *one="assssss"; char *two="assssss"; printf("please input two words:\n"); scanf("%s,%s",one,two);
printf("%s,%s\n",one,two); }
怎么每次输出都会比输入多几个莫名其妙的字符
scanf是按空格或回车就认为输入结束的,所以输入连续字符串按空格或字符串中有空格则认为空格前的连续字符串已经进入one指向开始的字符串,后面的连续字符进入two.
你还要检查一下,你的scanf里有个逗号,要照输,没有实际意义的。
// test 2 #include <stdio.h> int main() { char str[20] = "assssss"; // assignment to a char array char * one = str; // char pointer one pointe to this char array // now one is an address, under that address // there is a string "assssss" // and this string can be changed!!! one[0] = 'b'; // we set the first element of that string // a new value printf("%s", one); // you find now, this string is changed // now the string is "bssssss";
// but very important is the length of the char array must be langer than // the length of that string "assssss"; // otherwise, you will have problem again. // here 20 > 8, so it is ok. return 0; }// test 3 #include <stdio.h> int main() { char str1[50] = "assssss"; // now you have a place, in which you can // assign the value, change the value char str2[50] = "assssss"; // it is the same char *one= str1; char *two= str2; printf("please input two words:\n"); // you must pay attention here // scanf("%s, %s",one,two); it is not right, why? // you see between %s and %s there is a ',' // it is not permitted.
// so the right form looks like so scanf("%s %s" /* between them can be a space */, one, two);
printf("%s,%s\n",one,two); // it is ok, but the effect is others printf("%s %s\n", one, two);
return 0; // it is better, when you write this statement // so that, system know, the program safely // ended }you should understand, any constant can not be changed!!!
for example int a = 3; char * str = "assssss";
here 3 and "assssss" are constant value.
you can change the value from a, for example :
you write so later a = 5; it is ok. but the value 3 which will never be changable.
now let's see char * str = "assssss";
str is here just a pointer, that mean, str is just an address, under this address you will find the string value "assssss", and this string is an constant value, so it can not be changed.
so str[0] = 'b'; is not correct.
but char str[20] = "assssss"; here the meaning is something else, here you have allocated an memory place and with the 20 character spaces, in which you can store the character value, so you can later change the value in it.
so now, str[0] = 'b'; is ok.
sorry,maybe you are wrong,I had a try and the output tell me you mistaked,but I'm still
thanksful to you!
see:
#include <stdio.h> int main(){ char *a="assssss"; printf("%s",a); a[0]='b'; printf("%s",a); return 0; }
the output is :
assssss
bssssss