C++中的cin以及stringstream


主要根据该 参考链接进行的知识整理,主要自用笔记,若侵则删。

cin

cin>>

使用分隔符表示一个输入的结束。cin读取成功后,字符后面的分隔符留在缓冲区中,cin>>不对其进行处理
分隔符有:

  1. 空格(space)
  2. tab(tab)
  3. 换行(new-line character)
    但是,如果缓冲区中的第一个字符是分隔符时,cin会将其忽略并清除
// i/o example

#include <iostream>
using namespace std;

int main ()
{
  int i;
  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i;
  cout << " and its double is " << i*2 << ".\n";
  return 0;
}

输出为:

Please enter an integer value: 702
The value you entered is 702 and its double is 1404.

但是,如果键盘输入的i不是int类型呢?那么就会导致错误,导致i没有被正确的赋值。stringstreams则会更好的处理这种情况。

notes: Most programs are expected to behave in an expected manner no matter what the user types, handling invalid values appropriately.

cin>>a>>b

等价于:

cin >> a;
cin >> b;

cin and strings

cin也可以用来读取string

string mystring;
cin >> mystring;

但是,我们知道cin经常会处理分隔符,因此在此就限制了string只能是连续的word,而不能是phrase 或者sentence。

为了进一步的能够通过cin输入一段phrase或者sentence,引入了一个新的函数:getline,该函数接收两个参数,第一个参数为cin,第二个参数则为string变量,见以下示例:

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

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr); //第一个变量是cin,第二个是string变量
  cout << "Hello " << mystr << ".\n";
  cout << "What is your favorite team? ";
  getline (cin, mystr); // 在第二次使用getline的时候,程序只是简单的replace the previous content with the new one that is introduced.
  cout << "I like " << mystr << " too!\n";
  return 0;
}

输出为:

What's your name? Homer Simpson
Hello Homer Simpson.
What is your favorite team? The Isotopes
I like The Isotopes too!

此时,逐行的换行通过 press ENTER(or RETURN)来实现。

notes: Unless you have a strong reason not to, you should always use getline to get input in your console programs instead of extracting from cin.

stringstream

标准头文件<sstream>定义了一种称为stringstream的类型,该类型允许将字符串视为流,从而允许以与在cin和cout上执行的方式相同的方式从字符串中提取或插入字符串。

此功能对于将字符串以及数值之间的相互转换非常有用,即,可以间接的从标准输入中获取数值。比如字符串到数值的转换:

string mystr ("1204");
int myint;
stringstream(mystr) >> myint;

再比如:

// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string mystr;
  float price=0;
  int quantity=0;

  cout << "Enter price: ";
  getline (cin,mystr);
  stringstream(mystr) >> price;
  cout << "Enter quantity: ";
  getline (cin,mystr);
  stringstream(mystr) >> quantity;
  cout << "Total price: " << price*quantity << endl;
  return 0;
}

输出为:

Enter price: 22.25
Enter quantity: 7
Total price: 155.75

这相对于直接用cin输入数值的好处就是:
通过这种获取整行并提取其内容的方法,将获取用户输入的过程与将其赋给数值变量的两步操作分开。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FLOWVERSE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值