主要根据该 参考链接进行的知识整理,主要自用笔记,若侵则删。
cin
cin>>
使用分隔符表示一个输入的结束。cin
读取成功后,字符后面的分隔符留在缓冲区中,cin>>
不对其进行处理
分隔符有:
- 空格(space)
- tab(tab)
- 换行(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
输入数值的好处就是:
通过这种获取整行并提取其内容的方法,将获取用户输入的过程与将其赋给数值变量的两步操作分开。