C语言之随机数和字符串输入输出
一、隨機(jī)數(shù)產(chǎn)生函數(shù)
1、需要加入頭文件 #include<stdlib.h> 和 #include<time.h>
2、Rand是偽隨機(jī)數(shù)產(chǎn)生器,每次調(diào)用rand產(chǎn)生的隨機(jī)數(shù)是一樣的。
3、如果調(diào)用rand之前先調(diào)用srand就可以出現(xiàn)任意的隨機(jī)數(shù)。
4、只要能保證每次調(diào)用srand函數(shù)的時候,參數(shù)的值是不同的,那么rand函數(shù)就一定會產(chǎn)生不同的隨機(jī)數(shù)。
5、實(shí)例:
int main(void) {int t = (int)time(NULL);srand(t); //隨機(jī)數(shù)種子 int i;for(i=0;i<10;i++){printf("%d\n",rand()); //產(chǎn)生隨機(jī)數(shù)(每次運(yùn)行都會產(chǎn)生不同的隨機(jī)數(shù)) }return 0; }?
二、字符串輸入與輸出函數(shù)
1、scanf函數(shù)
char a[100] = {0};
scanf("%s",a); //表示輸入一個字符串,scanf是以回車鍵或空格作為輸入完成標(biāo)識的,但回車鍵本身并不會作為字符串的一部分。
注意:如果scanf參數(shù)中的數(shù)組長度小于用戶在鍵盤輸入的長度,那么scanf就會緩沖區(qū)溢出,導(dǎo)致程序崩潰。
例如:
#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()函數(shù)的使用
1、gets() 輸入,不能只用類似“%s”或者“%d”或者之類的字符轉(zhuǎn)義,只能接收字符串的輸入。
2、實(shí)例:
#include<stdio.h> #include<stdlib.h> int main(void) {char s[100] = {0};gets(s); // 輸入:hello world ,gets()函數(shù)同樣是獲取用戶輸入,它將獲取的字符串放入s中,僅把回車鍵視為結(jié)束標(biāo)志 ,但也有溢出問題 printf("-------\n");printf("%s\n",s); // 輸出:hello world return 0; }3、gets()獲取用戶輸入,atoi() 函數(shù)將字符串轉(zhuǎn)為數(shù)字 ,頭文件中加入 #include<stdlib.h>
#include<stdio.h> #include<stdlib.h> int main(void) {char a[100] = {0};char b[100] = {0};gets(a); // 獲取第一次輸入,a的對象只能是數(shù)組 ,不能轉(zhuǎn)義(字符串轉(zhuǎn)為數(shù)字),需要 使用專門的函數(shù) gets(b);int i1 = atoi(a); // 將字符串轉(zhuǎn)化為一個整數(shù) int i2 = atoi(b);printf("%d\n",i1+i2);return 0; }4、fgets()函數(shù)用法--gets()函數(shù)的升級版
#include<stdio.h> #include<stdlib.h> int main(void) {char c[10] = {0};fgets(c,sizeof(c),stdin);//第一個參數(shù)是char的數(shù)組,第二個參數(shù)是數(shù)組的大小,單位字節(jié),第三個參數(shù)代表標(biāo)準(zhǔn)輸入。// 輸入: hello world printf("%s\n",c);// 輸出:hello wor --> 它把字符串尾的 0 也包括在內(nèi)了,fgets()會自動截?cái)?#xff0c;防止溢出,所以很安全// 調(diào)用fgets()的時候,只要能保證第二個參數(shù)小于數(shù)組的實(shí)際大小,就可以避免緩沖區(qū)溢出的問題。 return 0;}5、puts()函數(shù),將用戶的輸入原樣打印出來
#include<stdio.h> #include<stdlib.h> int main(void) {char d[100] = {0};gets(d);printf("------\n");puts(d); //自動輸出,附帶換行 return 0 ;}6、fputs()函數(shù),是puts的文件操作版
#include<stdio.h> #include<stdlib.h> int main(void) {char e[100] = {0};fgets(e,sizeof(e),stdin); // hello world myloveprintf("----------\n");fputs(e,stdout); // hello world mylovereturn 0;}?
轉(zhuǎn)載于:https://www.cnblogs.com/schut/p/8552082.html
總結(jié)
以上是生活随笔為你收集整理的C语言之随机数和字符串输入输出的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ4810: [Ynoi2017]
- 下一篇: java 实现生产者-消费者模式