逗号分隔 整形 数字 输入 读取方法 C++
实际的在线编程笔试中,有的企业的输入隔间不是空格,而是逗号。利用C++不方便直接读入。
这是我认为简单的几个方法,记录一下。
1使用c++的stringstream流。
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec;
string stmp;
int itmp;
cin>>stmp;
replace(stmp.begin(), stmp.end(), ',', ' ');//#include <algorithm>
// for(int i=0;i<stmp.size();++i){
// if(stmp[i] == ',') stmp[i] = ' ';
// }
stringstream ss;//#include <sstream>
ss<<stmp;
while(ss>>itmp){
vec.push_back(itmp);
}
ss.clear();
cout << "输出" << endl;
for (int i = 0; i < vec.size(); ++i){
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
测试结果
1,2,3,4
输出
1 2 3 4
请按任意键继续. . .
2 使用c的scanf函数。
Microsoft Visual Studio这个IED认为sanf()函数不安全,此处暂以scanf_s()代替讲解
error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
在其他的IDE中,只需要将scanf_s()改成scanf(),并将读入长度参数去掉就行。两者效果一样:
//scanf_s("%d", &n, 1);
//scanf("%d", &n);
1、一连串以逗号分隔的n个数
如“1,2,3,4”这种:
int n;
vector<int> vec;
scanf_s("%d", &n, 1);//读入n,不需要逗号
//scanf("%d", &n);
for (int i = 0; i < n; ++i){
int tmp;
scanf_s("%d,", &tmp, 1);//分别读入n个数,'%d'后面加','
//scanf("%d,", &tmp);//分别读入n个数,'%d'后面加','
vec.push_back(tmp);
}
输出测试代码:
cout << "输出" << endl;
for (int i = 0; i < n; ++i){
cout << vec[i] << " ";
}
cout<<endl;
结果
4
1,2,3,4
输出
1 2 3 4
请按任意键继续. . .
2、一连串以空格分隔的n个数
如“1 2 3 4”这种
只要将上面的
scanf_s("%d,", &tmp, 1);
将逗号去掉,改为
scanf_s("%d", &tmp, 1);
即可。
去掉逗号,scanf_s中不需要加空格,尽管输入有空格
测试结果
4
1 2 3 4
输出
1 2 3 4
请按任意键继续. . .
3、矩阵数组
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int m;//行
int n;//每行的数字个数
vector<int> vectmp;
vector<vector<int> > vec;
scanf_s("%d,%d", &m, &n, 1, 1);
//scanf("%d,%d", &n,&m);
cout <<"m="<< m <<", n="<< n << endl;
for (int i = 0; i < m; ++i){
for (int j = 0; j < n; ++j){
int tmp;
scanf_s("%d,", &tmp, 1);
//scanf("%d,", &tmp);
vectmp.push_back(tmp);
}
vec.push_back(vectmp);
vectmp.clear();
}
cout << "输出:" << endl;
for (int i = 0; i < m; ++i){
vectmp = vec[i];
for (int j = 0; j < n; ++j){
cout << vectmp[j] << " ";
}
cout << endl;
}
return 0;
}
测试结果
2,3
m=2, n=3
1,2,3
4,5,6
输出:
1 2 3
4 5 6
请按任意键继续. . .
4、未告诉输入个数,以回车结束
vector<int> vec;
int tmp;
char ch = 'a';
for (int i = 0; i<100 && ch != '\n'; i++)
{
scanf_s("%d", &tmp, 1);//数字
//cout << "get_tmp:" << tmp << " ";
ch = getchar(); //空格或逗号
//cout << "get_ch:" << ch << endl;
vec.push_back(tmp);
}
cout << endl;
测试结果
1 2 3 4
输出
1 2 3 4
请按任意键继续. . .
12,11,10,9
输出
12 11 10 9
请按任意键继续. . .
END