码迷,mamicode.com
首页 > 编程语言 > 详细

C语言之随机数和字符串输入输出

时间:2018-03-12 21:51:48      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:键盘输入   运行   用户   main   nbsp   回车   不同   头文件   for   

一、随机数产生函数

  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;
    }

 

C语言之随机数和字符串输入输出

标签:键盘输入   运行   用户   main   nbsp   回车   不同   头文件   for   

原文地址:https://www.cnblogs.com/schut/p/8552082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!