i_am_so_stupid i_am_so_stupid - 1 year ago 72
C++ Question

Splitting text file on '=' delimiter line by line C++

I'm trying to make a dictionary in C++ but am having trouble splitting a text file on an '=' delimiter. Ideally it would be in an array of two. I want to take the left side of the '=' of the line into array[0] and the right side into array[1] and then use array[0] as the key and array[1] as the value through a premade insert function eg. dictionary.insert(array[0], array[1]). I've already built the dictionary logic but am having trouble splitting the lines.

Here's my (terrible) code that is not using the equal sign as the delimiter and therefore putting the '=' into array[1]:

int main() {

Dictionary englishToEsperanto;

ifstream infile("Dictionary.txt");

string line;
string arr[2];

if (infile.is_open())
while (getline(infile, line))
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 2) {
ssin >> arr[i];
for (i = 0; i < 2; i++) {
cout << arr[i] << ' ';
cout << endl;

cout << "Error opening file";

return 0;

Here's the first few lines of the text file:

aback, to take = surprizi.
abaft = posta parto.
abandon = forlasi.
abase = humiligi. [error in book: humilgi]
abash = hontigi.
abate (lower) = mallevi.
abate (speed) = malakceli.
abbey = abatejo.
abbot = abato.
abbreviate = mallongigi.
abdicate = demeti la re─Łecon.
abdomen = ventro.

Thanks for looking.

Answer Source

As suggested by @Thomas in comment, set '=' as delimiter for first getline, and default delimiter newline for second getline. Demo.

string before_equal, after_equal;
string arr[2];
while (getline(cin, before_equal, '=') && getline(cin, after_equal))
    stringstream ssin1(before_equal);
    stringstream ssin2(after_equal);
    if (ssin1.good() && ssin2.good()) {
        ssin1 >> arr[0];
        ssin2 >> arr[1];
    else continue;
    cout << arr[0] << ' ' << arr[1];
    cout << endl;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download