前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >cin的部分应用

cin的部分应用

作者头像
用户8247415
发布2021-04-13 16:13:48
4720
发布2021-04-13 16:13:48
举报
文章被收录于专栏:网页前端

No.1 cin.getline()

代码语言:javascript
复制
// instr2.cpp -- reading more than one word with getline
#include 
int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];

    cout << "Enter your name:\n";
    cin.getline(name, ArSize); // reads through newline
    cout << "Enter your favorite dessert:\n";
    cin.getline(dessert, ArSize);
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    return 0;
}

输出代码

代码语言:javascript
复制
Enter your name:
Dirk Hammernose
Enter your favorite dessert:
Radish Torte
I have some delicious Radish Torte for you, Dirk Hammernose.

getline函数读取整行,通过回车键输出的换行符来确定行尾。cin.getline()读取指定字符或换行符停止。 cin.getline(name,20) name是数组,20是元素个数

No.2 cin.get() 这是一种错误编译

代码语言:javascript
复制
// numstr.cpp -- following number input with line input
#include 
int main()
{
    using namespace std;
    cout << "What year was your house built?\n";
    int year;
    cin >> year;
    cout << "What is its street address?\n";
    char address[80];
    cin.getline(address, 80);
    cout << "Year built: " << year << endl;
    cout << "Address: " << address << endl;
    cout << "Done!\n";
    return 0;
}
代码语言:javascript
复制
What year was your house built?
1966
What is its street address?
Year built: 1966
Address:
Done!

cin读取年份,回车键生成换行符留在输出队列中,cin.getline()认为是一个空行,就将一个空字符串赋值给address数组,我们要解决就是丢弃这个换行符。 我们可以单独调用

代码语言:javascript
复制
cin>>year;
cin.get();

也可以用

代码语言:javascript
复制
(cin>>year).get()

cin.get()其他用法

代码语言:javascript
复制
// instr3.cpp -- reading more than one word with get() & get()
#include 
int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];

    cout << "Enter your name:\n";
    cin.get(name, ArSize).get(); // read string, newline
    cout << "Enter your favorite dessert:\n";
    cin.get(dessert, ArSize).get();
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    return 0;
}

输出

代码语言:javascript
复制
Enter your name:
Mai Parfait
Enter your favorite dessert:
Chocolate Mousse
I have some delicious Chocolate Mousse for you, Mai Parfait.

输出连在一起,这些应用需要实记。 补充:

在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档