#include <string>
#include <vector>
#include <fstream>
#include <iostream>
std::vector<std::string> split_string(const std::string& str,
const std::string& delimiter)
{
std::vector<std::string> strings;
std::string::size_type pos = 0;
std::string::size_type prev = 0;
while ((pos = str.find(delimiter, prev)) != std::string::npos)
{
strings.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
strings.push_back(str.substr(prev));
return strings;
}
std::vector< std::string > parse_CSV_line( const std::string& line, char delimiter )
{
bool inQuotes = false;
std::string currentValue;
std::vector< std::string > record;
for ( std::string::size_type i = 0; i < line.length(); ++i )
{
const char currentChar = line[ i ];
if ( ! inQuotes && currentValue.empty() && currentChar == '"' )
{
inQuotes = true;
}
else if ( inQuotes && currentChar == '"' )
{
if ( i + 1 < line.length() && line[ i + 1 ] == '"' )
{
currentValue.push_back( currentChar );
++i;
}
else
{
inQuotes = false;
}
}
else if ( ! inQuotes )
{
if ( currentChar == delimiter )
{
record.push_back( currentValue );
currentValue.clear();
}
else if ( currentChar == '\r' || currentChar == '\n' )
{
record.push_back( currentValue );
return record;
}
else
{
currentValue.push_back( currentChar );
}
}
else
{
currentValue.push_back( currentChar );
}
}
record.push_back( currentValue );
return record;
}
std::string readFileIntoString( const std::string& fileName )
{
std::ifstream ifs( fileName, std::ios::in );
if ( ! ifs )
{
std::cerr << "Failed to open file for reading!\n";
return std::string();
}
return std::string( ( std::istreambuf_iterator< char >( ifs ) ), std::istreambuf_iterator< char >() );
}
int main()
{
const std::string fileContent = readFileIntoString( "D:\\tmp\meineDatei.txt" );
if ( fileContent.empty() )
{
// war wohl nix
return 1;
}
const std::vector< std::string > lines = split_string( fileContent, "\n" );
for ( auto it = lines.begin(); it != lines.end(); ++it )
{
const std::vector< std::string > fieldsInThisLine = parse_CSV_line( *it, ';' );
const std::string id_string = fieldsInThisLine.at( 0 );
const std::string title_string = fieldsInThisLine.at( 1 );
const std::string author_string = fieldsInThisLine.at( 2 );
// ...
}
return 0;
}