数字字符串的输入:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> vec;//["20,30,40", 50,60,70", "80,90,100"]
string str;
//while(getline(cin, str))//用getline可以输入空格,只用cin代表遇到空格即结束
while(cin >> str)//输入后enter+ctrl+Z+enter
vec.push_back(str);
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << endl;
system("pause");
return 0;
}
对数字字符串进行分割:
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h> //sscanf()在C语言中包含在此头文件中
#include <string.h> //strtok()在C语言中包含在此头文件中
using namespace std;
int main()
{
string str;
cout<<"Input a numbers string with , :"<<endl;
while(cin >> str)
{
//string转化为C字符串char *,这一步C++到C的转换很重要
char *s = (char *)str.c_str();
const char *split = ",";
//以逗号为分隔符拆分字符串,第一次调用后相当于用NULL替换了第一个逗号,
char *p = strtok(s, split);
vector<int> nums;
int num;
while(p != NULL)
{
//将第一个子C字符串char*转化为int
sscanf(p, "%d", &num);
nums.push_back(num);
p = strtok(NULL, split);//多次调用分割函数,每次都以NULL作为子串起点
}
cout<<"Output:"<<endl;
for(int i = 0; i < nums.size(); i++)
{
cout << nums[i] << " ";
}
}
return 0;
}
#include <iostream>
#include <stdio.h>
#include <string.h> //strtok()函数包含在此头文件
int main ()
{
char str[] ="a,b3c,cf,d*e";
const char * split = ",";
char * p;
p = strtok (str, split);
while(p != NULL)
{
printf ("%s\n", p);
p = strtok(NULL, split);
}
system("pause");
return 0;
}