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
>Solution :
- Put the tokens into a vector instead of printing.
- 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);
}