引言

  因为在日常的学习过程中经常会发现CPP要处理一些带有空格的输入,并且学要以习性读取后进行拆分,甚至有可能出现空格前后的数据格式不同的情况,所以就把最好用的一个模块放在这里进行一下介绍。

使用介绍

个人十分推荐使用sstream头文件中带有的istringstream。这个可以较为方便得使用。先说明它只能处理带有空格的一行的字符串,并且在输出时可以根据输出的对象自动转变类型,所以是非常好用的。原理不是很好介绍,到时候有时间再把这一块补上。下面就是直接看代码领悟一下就可以了。

具体代码

这里提供两段代码分别是两个使用方式,都可以进行使用,请根据情况自行选择。事先说明,请在程序的开头使用#include<sstream>

1
2
3
4
5
6
7
8
9
while (getline(cin, temp)) {
if (temp.size() == 0)
break;
istringstream ss(temp);
int temp_num;
while (ss >> temp_num) {
Product_info.push_back(temp_num);
}
}

然后是另一段代码

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
Bank bank;
int index = 0;
string input;
string method, name;
int id, type;
double money;
getline(cin, input);
while (strcmp(input.c_str(), "end") != 0) {
istringstream ss(input);
ss >> method;
if (strcmp(method.c_str(), "createAccount") == 0) {
ss >> type;
bank.CreateAccount(type);
}
else if (strcmp(method.c_str(), "createCustomer") == 0) {
ss >> name;
bank.CreateCustomer(name);
}
else if (strcmp(method.c_str(), "addToCustomer") == 0) {
ss >> id>>name;
bank.AddToCustomer(id,name);
}
else if (strcmp(method.c_str(), "accountDeposit") == 0) {
ss >> id>>money;
bank.AccountDeposit(id,money);
}
else if (strcmp(method.c_str(), "accountWithdraw") == 0) {
ss >> id >>money;
bank.AccountWithdraw(id,money);
}

第二段代码是一种比较灵活的运用方式,到时候再加吧,最近时间实在是有点紧张。