字符串輸入與輸出

void test_string()
{
    /*
    1、聲明字符串
       數組word是常量;
       指針wd是變量;
       所以,只有指針能進行遞增操作!!!
    */
    char word[] = "We are here today!";
    char *wd = "Where are you now?";

    int i = 0;
    //數組遍歷
    while(*(word+i)!='\0')
    {
        putchar(*(word+i));
        i++;
    }
    //指針遍歷
    while(*(wd)!='\0')
    {
        putchar(*(wd++));
    }
    /*
    2、puts只用於輸出字符串,並自帶回車
    */
    //puts(word);
    //puts(wd);
}
void test_gets_puts()
{
    /* 3、
    gets():讀取整行輸入,直至遇到換行符,然後丟棄換行符,儲存其餘字符,
            並在這些字符的末尾添加一個空字符使其成爲一個字符串.
    puts():顯示字符串,並在末尾添加換行符
    */
    char words[LEN];
    puts("Enter a string:");
    gets(words);
    puts(words);
    puts("Done!");
    /*
    Note:
        gets()函數不安全,它只知道數組的首地址,不知道數組的長度,
        如果輸入的字符串過長,會導致緩衝區溢出(Buffer Overflow)。
    */
}

void test_fgets_fputs()
{
    char words[LEN];
    puts("Enter:");

    fgets(words,LEN,stdin);//讀入從鍵盤輸入的數據,則以stdin(標準輸入)作爲參數
    fputs(words,stdout);//顯示在計算機顯示器上,則以stdout(標準輸出)作爲參數

    puts("Done!");
    /* 4、
    case 1:字符串不超長
        輸入:
            I am ok
            實際輸入:I am ok\n  因爲敲了回車,所以加\n;
            word數組中保存:I am ok\n\0  因爲要變成字符串,所以末尾加\0;
            gets()會丟棄換行符,所以gets()的實際輸入:I am ok
        輸出:
            I am ok
            Done!
    case 2:字符串超長
        輸入:
            I am your friend
            實際輸入:I am your friend\n
            word數組中保存:I am your\0  因爲fgets()一次最多讀入LEN - 1個字符
        輸出:
            I am yourDone! 
            fputs()不會自動添加換行符;
    */
}
/* 5、
空字符:'\0',整數類型,用數值0來表示;空字符是一個字符,佔1字節;
空指針:NULL,指針類型,也用數值0來表示;空指針是一個地址,通常佔4字節;
*/

void test_scanf()
{
    /* 6、
    scanf()更像是“獲取單詞”函數,而不是“獲取字符串”函數;
    scanf()返回一個整數值,該值等於scanf()成功讀取的項數或EOF(讀到文件結尾時返回EOF)。
    */

    char name1[11], name2[11];
    int count;
    printf("Please enter 2 names.\n");
    count = scanf("%5s %10s",name1,name2);
    printf("I read the %d names %s and %s.\n",count,name1,name2);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章