C語言之隨機數和字符串輸入輸出


一、隨機數產生函數

  1、需要加入頭文件 #include<stdlib.h> 和 #include<time.h>

  2、Rand是偽隨機數產生器,每次調用rand產生的隨機數是一樣的。

  3、如果調用rand之前先調用srand就可以出現任意的隨機數。

  4、只要能保證每次調用srand函數的時候,參數的值是不同的,那么rand函數就一定會產生不同的隨機數。

  5、實例:

int main(void) { int t = (int)time(NULL); srand(t); //隨機數種子 
    int i; for(i=0;i<10;i++) { printf("%d\n",rand()); //產生隨機數(每次運行都會產生不同的隨機數) 
 } return 0; }

 

二、字符串輸入與輸出函數

  1、scanf函數

    char a[100] = {0};

    scanf("%s",a); //表示輸入一個字符串,scanf是以回車鍵或空格作為輸入完成標識的,但回車鍵本身並不會作為字符串的一部分。

    注意:如果scanf參數中的數組長度小於用戶在鍵盤輸入的長度,那么scanf就會緩沖區溢出,導致程序崩潰。

    例如:

#include<stdio.h>
int main(void) { char s[10] = {0}; scanf("%s",s); int i; for(i=0;i<10;i++) { printf("%d",s[i]); } printf("%s\n",s); return 0; }

  2、gets()函數的使用

    1、gets() 輸入,不能只用類似“%s”或者“%d”或者之類的字符轉義,只能接收字符串的輸入。

    2、實例:

#include<stdio.h> #include<stdlib.h>
int main(void) { char s[100] = {0}; gets(s); // 輸入:hello world ,gets()函數同樣是獲取用戶輸入,它將獲取的字符串放入s中,僅把回車鍵視為結束標志 ,但也有溢出問題 
    printf("-------\n"); printf("%s\n",s); // 輸出:hello world 
     
    return 0; }

  3、gets()獲取用戶輸入,atoi() 函數將字符串轉為數字 ,頭文件中加入 #include<stdlib.h> 

#include<stdio.h> #include<stdlib.h>
int main(void) { char a[100] = {0}; char b[100] = {0}; gets(a); // 獲取第一次輸入,a的對象只能是數組 ,不能轉義(字符串轉為數字),需要 使用專門的函數 
 gets(b); int i1 = atoi(a); // 將字符串轉化為一個整數 
    int i2 = atoi(b); printf("%d\n",i1+i2); return 0; }

  4、fgets()函數用法--gets()函數的升級版

#include<stdio.h> #include<stdlib.h>
int main(void) { char c[10] = {0}; fgets(c,sizeof(c),stdin);//第一個參數是char的數組,第二個參數是數組的大小,單位字節,第三個參數代表標准輸入。 // 輸入: hello world 
    printf("%s\n",c);// 輸出:hello wor --> 它把字符串尾的 0 也包括在內了,fgets()會自動截斷,防止溢出,所以很安全 // 調用fgets()的時候,只要能保證第二個參數小於數組的實際大小,就可以避免緩沖區溢出的問題。 
    return 0; }

  5、puts()函數,將用戶的輸入原樣打印出來

#include<stdio.h> #include<stdlib.h>
int main(void) { char d[100] = {0}; gets(d); printf("------\n"); puts(d); //自動輸出,附帶換行 
    return 0 ; }

  6、fputs()函數,是puts的文件操作版

#include<stdio.h> #include<stdlib.h>
int main(void) { char e[100] = {0}; fgets(e,sizeof(e),stdin); // hello world mylove
    printf("----------\n"); fputs(e,stdout); // hello world mylove
    return 0; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM