Hello i have text file has each line like below.
101,Tarkan,E,1,22,1,1,0
102,Mustafa,E,2,54,0,0,1
103,Seher,K,2,65,0,1,0
104,Ali,E,1,88,0,1,0
105,Ahmet,E,3,12,1,0,0
106,Osman,E,5,2,0,0,0
107,Remziye,K,3,63,0,0,1
108,Ayse,K,1,10,0,0,0
109,Esma,K,2,25,0,0,0
110,Mahmut,E,1,35,0,0,0
Here is my code. I need to split and assign to related variables using regex with C++
string line;
string items[8];
int i=0,j=0;
if (!fkisiler)
cout<<"kisiler.txt bulunamadi";
else{
while (getline(fkisiler,line)){
stringstream ss(line);
string item;
while (getline(ss,item,',')){
items[i]=item;
cout<<items[i]<<"\t";
i++;
}
kisiler[j].id=stoi(items[0]);
kisiler[j].isim=items[1];
kisiler[j].cinsiyet=items[2][0];
kisiler[j].mahalle=stoi(items[3]);
kisiler[j].yas=stoi(items[4]);
kisiler[j].covid19=stoi(items[5]);
kisiler[j].kronik=stoi(items[6]);
kisiler[j].il_disi=stoi(items[7]);
cout<<"\n*****\n";
j++;
}
}
Not sure regex is better, but you might do:
const std::regex reg{R"(^(\d+),(\w+),(\w),(\d+),(\d+),(\d+),(\d+),(\d+)$)"};
while (std::getline(fkisiler, line)){
std::smatch items;
if (std::regex_match(line, items, reg)) {
kisiler[j].id = stoi(items[1]);
kisiler[j].isim = items[2];
kisiler[j].cinsiyet = items[3][0];
kisiler[j].mahalle = stoi(items[4]);
kisiler[j].yas = stoi(items[5]);
kisiler[j].covid19 = stoi(items[6]);
kisiler[j].kronik = stoi(items[7]);
kisiler[j].il_disi = stoi(items[8]);
std::cout << "\n*****\n";
j++;
} // else handle error
}
you can use this split()
function to split a string with a delimiter that you choose. You can even choose another delimiter where delimiter.length() > 1
, like "><", ",.,"
...etc
std::vector<std::string> split(std::string& t, std::string delimiter)
{
char* p = &t.at(0);
std::string result = "";
std::vector<std::string> out = {};
size_t sum;
for (size_t i = 0; i < t.length(); i++)
{
if (*p != delimiter[0])
{
result.push_back(*p);
p++;
sum = 1;
}
else
{
char* d = &delimiter.at(0);
std::string s = "";
for(size_t j = 0; j < delimiter.length(); j++)
{
if(*p == *d)
{
s.push_back(*p);
d++;
p++;
sum = j+1;
if (j > 0)
++i;
}
else
{
result +=s;
break;
}
}
if (sum == (delimiter.length()))
{
out.push_back(result);
result="";
}
}
}
out.push_back(result);
return out;
}
void printed (std::vector<std::string> v)
{
for(std::vector<std::string>::iterator it = v.begin(); it < v.end(); it++)
std::cout << *it << std::endl;
}
int main()
{
std::string text = "101,Tarkan,E,1,22,1,1,0";
std::string delimter = ",";
std::vector<std::string> out = {};
out = split(text, delimter);
printed(out);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.