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

C++常用的输入函数总结

时间:2015-05-10 23:42:42      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

主要的输入输出函数有6种:cin, cin.get() , cin.getline() ,getline()  , gets()  ,getchar()

cin

(1)根据变量的类型读取数据

结束条件:回车键、空格键、TAB

结束符的处理:缓冲区中丢弃使输入结束的结束符(回车键、空格键、TAB)

#include <iostream>
using namespace std;
void main()
{
    int a,b;
    cin>>a>>b;
    cout<<a+b<<endl;

}

(2)接收字符串

#include <iostream>
using namespace std;
void main()
{
    char ch[20];
    cin>>ch;
    cout<<ch<<endl;

}

输入:helloworld

输出:helloworld

输入:hello world(此时是空格键,表示输入结束)

输出:hello

cin.get()

(1)接收一个字符

结束条件:回车键

结束符处理:缓冲区的Enter不丢弃

#include <iostream>
using namespace std;
void main()
{
    char ch;
    //ch = cin.get();
    cin.get(ch);
    cout<<ch<<endl;
}

输入:he llo

输出:h

(2)接收一行字符串,cin.get(数组名,接收字符的数目), 

结束条件:Enter

结束符处理:缓冲区的Enter丢弃

#include <iostream>
using namespace std;
void main()
{
    char ch[20];
    cin.get(ch,10);
    cout<<ch<<endl;
}

 

输入:hello world

输出:hello wor(9个字符加上‘/0‘)

cin.getline()

接收一个字符串可以接受空格,

cin.getline(数组名,长度,结束符)  与 cin.get(数组名,长度,结束符)用法是一样的

区别:当输入的字符串的长度超过指定的长度时,cin.getline()会出错,cin不会执行。

而cin.get()继续执行下次是从缓冲区内去字符

结束条件:Enter

结束符处理:丢弃Enter

#include <iostream>
using namespace std;
void main()
{
    char name[20];
    char shcool[30];
    cin.getline(name,10);
    cin.getline(shcool,20);
    cout<<"name:"<<name<<endl;
    cout<<"shcool:"<<shcool<<endl;
}

技术分享

可以看到是上面的输出的区别。

getLine()

接收字符串,可以接受空格,是String流,注意头文件

#include <iostream>
#include <string>
using namespace std;

int main ()

{
    string str;
    getline(cin,str);
    cout<<str<<endl;
}

gets()

#include <iostream>
#include <string>
using namespace std;

int main ()

{
    char ch[20];
    gets(ch);
    cout<<ch<<endl;
}

getchar()

接收一个字符,是C语言的函数,

#include <iostream>
#include <string>
using namespace std;

int main ()

{
    char ch;
    ch = getchar();
    cout<<ch<<endl;
}

 

C++常用的输入函数总结

标签:

原文地址:http://www.cnblogs.com/junjian/p/4493238.html

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