【问题标题】:How to copy words from a file spearated by semicolon (;) into an array in C++? [duplicate]如何将分号 (;) 分隔的文件中的单词复制到 C++ 中的数组中? [复制]
【发布时间】:2016-03-11 11:22:55
【问题描述】:

这是我在 StackOverflow 上的第一个问题,如果能得到任何帮助,我将不胜感激。

我有一个文件,其中包含一个德语单词及其英语翻译,每行用分号分隔。

看起来像这样:

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

我创建了以下结构:

struct Entry

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

我要做的是创建一个函数,它将每行的第一个单词复制到字符串german,然后跳过分号并将行中的第二个单词复制到字符串english,这应该逐行写入变量类型Entry的数组中。

这是我创建的函数 - 当然它缺少几行可以进行实际复制的行。 :)

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

提前致谢。

【问题讨论】:

标签: c++ arrays file copy


【解决方案1】:

使用string.find()string.substr() 的组合,您可以通过分隔符分割字符串。使用getline,您可以逐行读取文件。然后您需要创建新结构并将它们添加到数组中。在此代码的主要部分,对数组进行一些谷歌搜索,您可以自己找出其余部分(SO 不是代码编写服务)。欢迎来到 SO!

  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"; 

【讨论】:

  • 你应该在find之后检查delimiterpos != std::string::npos
猜你喜欢
  • 2020-10-23
  • 2012-04-11
  • 2014-09-25
  • 2017-09-28
  • 2016-05-11
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
相关资源
最近更新 更多