Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign 2 strings from a text file to 2 variables?

I’m trying to assign 2 strings separated by a dash - in a text file to 2 variables so I can perform insertion in my program. This is a sample of the text file, it’s in the format Word-Meaning:

language-the method of human communication
map-a diagrammatic representation of an area

This is my program:

void insert(const string& word, const string& meaning)
{
    // Do something
}

int main()
{
    string word, meaning;
    ifstream fin("example.txt");

    while (!fin.eof()) {
        getline(fin, word);
        istringstream iss(word);
        string token;
        while (getline(iss, token, '-'))
        {
            cout << token << endl;
        }
    }

    // How can I assign the tokens above to these 2 variables ?
    insert(word, meaning);
}

How can I assign the tokens above to the 2 string variables ? Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. Put the tokens into a vector instead of printing.
  2. Assign the elements of the vector to the variables after checking if the vector has enough elements.

Also note that your usage of while (!fin.eof()) is wrong.

// #include for required headers here
#include <vector> // add this if this is not included in the original code

void insert(const string& word, const string& meaning)
{
    // Do something
}

int main()
{
    string word, meaning;
    ifstream fin("example.txt");

    while (getline(fin, word)) {
        istringstream iss(word);
        std::vector<string> tokens;
        string token;
        while (getline(iss, token, '-'))
        {
            //cout << token << endl;
            tokens.push_back(token);
        }
        // assign the elements of the vector to variables
        if (token.size() >= 2)
        {
            word = tokens[0];
            meaning = tokens[1];
        }
    }

    // warning: only last assigned values of word and meaning will be passed
    insert(word, meaning);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading