您的位置:首页 > 其它

关于gets()/puts() 和getchar()/putschar() 和getline()

2015-07-01 12:41 387 查看
gets()/puts() 是对字符串的操作,getchar()/putschar()是对字符的操作

gets()从标准设备读取字符直到遇到换行符为止;

getchar()读取标准输入的下一个字符,直到遇到文件结束标志或发生错误。

puts()将buffer中的字符输出到标准输出,直到遇到空字符('\0')为止;

putchar(c)将c对应值输出到标准输出。成功的话返回c失败返回EOF

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    char c;
    c=getchar();
    cout <<c <<endl;
    //putchar(c);

    cout << "------------------"<< endl;
    fflush(stdin);//清空输入缓冲区,通常是为了确保不影响后面的数据读取
    char s[20];
    gets(s);
   // cout << s << endl;
    puts(s);
    //puts("");//换行
    cout <<"this is end !"<< endl;
    return 0;
}
注意:puts()函数具有自动换行的功能,就像puts("");就相当于cout << endl;



#include <stdio.h>
int main()
{
    char c;
    while((c = getchar()) != EOF)
        putchar(c);
    return 0;
}



#include <stdio.h>
int main()
{
    char s[20];

    while(gets(s) != NULL)
    puts(s);
    return 0;
}



getline不是C库函数,而是C++库函数。它会生成一个包含一串从输入流读入的字符的字符串,有两种传参方式:

//用字符数组
ifstream fin("in.dat");
char line[100];
while(fin.getline(line,100))	
{
    cout<<line<<endl;
}

//用字符串	
ifstream fin("in.dat");
string s;
while(getline(fin,s))
{
    cout<<s<<endl;
}


第一个getline()是istream中,把从文件中读到的值赋予line数组,第一个是数组名,第二个是读到值的长度,还有一个参数缺省,用来设置读到特定字符时停止。

第二个是在string 中,也是接收三个参数,一个输入流对象和一个string对象,第三个参数和前一个getline()中一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: