← 返回首页
C语言系列教程(十八)
发表时间:2021-03-25 23:18:24
字符串输入和输出

1.字符串的输出

字符串输出常用函数有两个,它们分别是: puts():输出字符串并自动换行,该函数只能输出字符串。 printf():通过格式控制符%s输出字符串,不能自动换行。除了字符串,printf() 还能输出其他类型的数据。

实例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {

    char str1[30]="abcdefghijklmnopqrstuvwxyz";
    char str2[30];
    char str3[30]={0};

    for(int j=0,i=97;i<123;j++,i++){
       str2[j]=i;
       str3[j]=i;
    }
    printf("%s",str1);
    printf("%s",str2);
    printf("%s",str3);

    printf("\n------out with puts---------\n");
    puts(str1);
    puts(str2);
    puts(str3);

    return 0;
}

运行结果: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ------out with puts--------- abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz

2.字符串输入 在C语言中,有两个函数可以让用户从键盘上输入字符串,它们分别是: scanf():通过格式控制符%s输入字符串。但是无法读取含有空格的字符串。除了字符串,scanf() 还能输入其他类型的数据。 gets():直接输入字符串,并且可以输入带空格的字符串。

实例:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
    char str[10];
    scanf("%s",&str);
    puts(str);
    return 0;
}

运行结果: hello world hello

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){

    char str[10];
    gets(str);
    puts(str);
    return 0;
}

运行结果: hello world hello world