如何将分号 (;) 分隔的文件中的单词复制到 C++ 中的数组中?
How to copy words from a file spearated by semicolon (;) into an array in C++?
这是我在 Whosebug 上的第一个问题,如果能得到任何帮助,我将不胜感激。
我有一个文件,其中包含一个德语单词及其英文翻译,每行用分号分隔。
看起来像这样:
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);
}
提前致谢。
使用 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";
这是我在 Whosebug 上的第一个问题,如果能得到任何帮助,我将不胜感激。
我有一个文件,其中包含一个德语单词及其英文翻译,每行用分号分隔。
看起来像这样:
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);
}
提前致谢。
使用 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";