1. 程式人生 > >字符串的輸入scanf 和gets

字符串的輸入scanf 和gets

位置 不同 方式 大於 get scanf clu 空格 hello

#include<stdio.h> #include<string.h> #define N 100 int main(int argc, const char *argv[]) { char str1[N]; char str2[N]; ①scanf("%s",str1); ②gets(str1); printf("%s\n",str1); return 0; } ①這種情況如果是打印Hello World這種中間位置有空格的字符串會出現只打印Hello的情況, 因為scanf函數中,只有%c才能打印空格這樣的字符,而%s是不認識空格這樣的字符型常量 ②gets()這個函數就沒有以上的顧慮,但是不建議使用這樣的輸入方法,#define N 100這裏 定義的是字符串能夠占用的內存,gets()是將輸入的字符串全部輸入,這樣就會造成如果輸 入的字符串的長度大於定義的內存就會占用非法的內存空間 [email protected]
/* */:~/cwx$ ./zifuchuan1 i am student!!! i come from yancheng i am student!!! i come from yancheng *** stack smashing detected ***: ./zifuchuan1 terminated (stack smashing detected是分配的空間不足的提示) 另外還有一個註意點就是scanf("%s",str1)與之前輸入的方式不同的是字符串在輸入的時候是不 需要加上&這樣的取地址符,因為str1作為字符串名其實就是地址常量

字符串的輸入scanf 和gets