E
E
Eugene2020-09-26 14:42:19
C++ / C#
Eugene, 2020-09-26 14:42:19

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;

    }


Error on line 18:
error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string'} to 'char*'

I understand that he can't convert string to char, but how to solve this problem - sincerely Xs.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shatunov, 2020-09-27
@jenya92

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 question

Ask a Question

731 491 924 answers to any question