C++ 字符串的输入

每次读取一个单词用cin

读取一行字符串:

    (1)面向行的输入:getline() 通过换行符来确定行尾,但不保存换行符

            getline( )函数读取整行 回车键输入的换行符来确定结尾 调用方法:cin.getline(   ) 参数:第一个参数数组名称,第二个参数读取的字符数

#include<iostream>
int main() 
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name, ArSize);
cout<<"Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious" << dessert;
cout << "for you" << name << ".\n";
return 0;

}

    (2)面向行的输入 get()并不在读取并丢弃换行符 而是将其留在输入队列中

        cin.get(name,ArSize)

cin.get(数组名,数组数量)。get()

#include<iostream>
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();
cout << "Enter your dessert\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << "for you." << name << ".\n";
return 0;

}

为什么使用get() 而不是getline()呢 首先老式实现没有getline(),其次是get()可以知道是读取了整行,而不是由于数组已经填满

混合输入字符串和数字

//混合输入字符串和数字
#include<iostream>
int main() 
{
using namespace std;
cout << "What year was your house build?\n ";
int year;
cin >> year;
cin.get();
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "your build:" << year << endl;
cout << "your address:" << address << endl;
return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值