1

This is my first question on StackOverflow and I would really appreciate any help I can get.

I have a file with a German word and its English translation separated by a semicolon in each line.

It looks something like this:

Hund;dog
Katze;cat
Pferd;horse
Esel;donkey
Fisch;fish
Vogel;bird

I have created the following structure:

struct Entry

{
    string english = "empty";
    string german = "empty" ;
};

What am trying to do is to create a function that would copy the first word of each line to the string german and then skip the semicolon and copy the second word in the line to the string english and this should be done line by line into an array of the variable type Entry.

This the function I created - of course it's missing a few lines that would do the actual copying. :)

void importFile(string fname, Entry db[])
{
    ifstream inFile;
    inFile.open(fname);
}

Thanks in advance.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Mina
  • 75
  • 6
  • You could read the file using a `CSV` reader (search this site for examples). But for such a simple format you can just read each line with `getline` into a `std::string`, search for the semi-colon, and then get substrings via the `std::string` member function `substr`. – Anon Mail Dec 06 '15 at 22:51
  • i think that you should search in google first since it's a question which was answered many times already. for example here: https://stackoverflow.com/questions/7868936/read-file-line-by-line and here https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c or that one https://stackoverflow.com/questions/1474790/how-to-read-write-into-from-text-file-with-comma-separated-values with that links u can easily create this code: edit: nvm. u have an answer in another post. – Dominik Dec 06 '15 at 23:01

1 Answers1

1

Using a combination of string.find() and string.substr() you can split a string by a delimiter. With getline you can read line by line of the file. Then you need to create new structs and add them to the array. Hereby the main part of the code, do a bit of googling to arrays and you can figure out the rest yourself.

  string line;
  string english, german;
  int delimiterpos;
  Entry mEntry;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      //line now consists of the german;english
      delimiterpos = line.find(";");
      german = line.substr(0,delimiterpos);
      english = line.substr(delimiterpos+1,line.size());
       //create a new struct and add it to array.
        mEntry = new Entry();
        mEntry.german= german;
        mEntry.english = english;
        // add to some array here
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
Dharman
  • 30,962
  • 25
  • 85
  • 135
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62