getline()

1
istream& getline (istream& is, string& str, char delim);

delim(分隔符),表示遇到这个字符停止读入,系统默认该字符为’\n’ 。

1
2
3
string line;
getline (cin, line, '*');
cout << line << endl;

当输入 24gm is * the best ,时 读入输入流的只有 24gm is, 后面的并没有存入line中。
注意, 由于此时delim设定为`
所以即使输入 回车键 也不会停止读入,只有遇到*` 时才会停止读入。

c++读取以逗号为分隔符的一串数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<vector>
#include<sstream>

using namespace std;
int main()
{
string s;
vector<int> v;
getline(cin, s);
istringstream is(s);
int inter;
char ch;
while (is >> inter)
{
v.push_back(inter);
is >> ch; //把数字后面的逗号读取走,这样下次循环时 is中就是从逗号后面的数字开始了
}
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<endl;
return 0;
}


关于上述程序注释的说明:
```C++
string s;
string s1;
vector<int> v;
getline(cin, s);
istringstream is(s);
int inter;
char ch;
is >> inter;
is >> ch;
is >> s1;


cout << "inter: " << inter << endl;
cout << "ch: " << ch << endl;
cout << "s1: " << s1 << endl;

输出如下:


输入 24,35,55,85,135
输出 24 35 55 85 135

注意在vs中 进入黑色的命令行界面时 要注意输入法是否是英文, 否则会出现错误。
下图这样的输入 逗号后似乎还有空格, 这样程序输出就会错误。

正确输入如下

stringstream通常是用来做数据转换的

1
2
3
4
string result=”10000”;
int n=0;
stream<<result;
stream>>n;//n等于10000
0%