Answer the question
In order to leave comments, you need to log in
How to split a string by delimiter?
I decided to store the database in a file. In the system, store records that are separated by a semicolon. The base will be small, there are only three values, so I decided not to bother too much. But the problem came from where I did not expect. It is not possible to split the received string by the delimiter. The code itself looks like this:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]){
ifstream fin;
fin.open("/home/MyUzer/cpp/baze.txt");
string FileLine;
if (fin.is_open()){
cout << "Файл успешно открыт" << endl;
while(getline(fin, FileLine)){ // Считываем поочерёдно строки из файла
cout << "Строка: " << FileLine << endl;
char *pch = strtok (FileLine, ";"); // разбиваем по разделителю
while (pch != NULL){ // Вводим строки
cout << pch << ";" << endl;
pch = strtok (NULL, ";");
}
}
}
else
cout << "Ошибка открытия файла" << endl;
return 0;
}
Answer the question
In order to leave comments, you need to log in
This is an easy way to split a string into substrings.
inline std::vector<std::string_view> SplitString( std::string_view input_string, const char separator )
{
std::vector<std::string_view> parts;
size_t part_length = 0;
while( ( part_length = input_string.find( separator ) ) != input_string.npos )
{
parts.emplace_back( input_string.data(), part_length );
input_string.remove_prefix( part_length + 1 );
}
if( !input_string.empty() )
{
parts.push_back( std::move( input_string ) );
}
return parts;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question