从文件中读入文本,文本内容为几个字符串,用逗号间隔,将其中同时含有字母和数字的字符串去除,留下仅仅只包含字母或数字的字符串,然后进行排序,排序规则如下:
(1) 数字的串按数字大小排序
(2) 字母的串按ASCII码排序
(3) 所有数字排在字母前
最后将结果输出的文件中。
例如:hello, He, 1b, 2b, 55, 9, 6b ----> 9 55 He hello
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
//0 char and num
//1 all char
//2 all num
int StrType(char *s)
{
bool isChar = false;
bool isNum = false;
char *c = s;
while (*c != '\0')
{
if(isdigit(*c))
{
isNum = true;
}
else
{
isChar = true;
}
c++;
}
if(isChar && isNum)
{
return 0;
}
else if(isChar && !isNum)
return 1;
else if (!isChar && isNum)
return 2;
}
int main()
{
ifstream inFile;
inFile.open("data.txt");
vector<int> intVec;
vector<string> strVec;
string s;
while (getline(inFile,s))
{
int len = s.length();
char *cstr = new char[len + 1];
strcpy(cstr,s.c_str());
char *p = strtok(cstr,",");
while(p)
{
int sType = StrType(p);
if( sType == 1)
{
string sTmp(p);
strVec.push_back(sTmp);
}
else if(sType == 2)
{
int iTmp = atoi(p);
intVec.push_back(iTmp);
}
p = strtok(NULL,",");
}
}
sort(intVec.begin(),intVec.end());
sort(strVec.begin(),strVec.end());
ofstream outFile;
outFile.open("result.txt");
for(int i = 0;i<intVec.size();i++)
{
outFile<<intVec[i]<<" ";
}
for (int i = 0;i<strVec.size();i++)
{
outFile<<strVec[i]<<" ";
}
inFile.close();
outFile.close();
system("pause");
return 0;
}
//English,She,2n,77,8,0k