【发布时间】:2014-12-03 21:04:34
【问题描述】:
我正在用 c++ 编写一个驱动程序,它最终需要将两个字符串传递给我在单独文件中编写的函数。我正在从格式如下的文件中读取数据:
ac: and
amo: love
amor: love
animal: animal
annus: year
ante: before, in front of, previously
antiquus: ancient
ardeo: burn, be on fire, desire
arma: arms, weapons
atque: and
aurum: gold
aureus: golden, of gold
aurora: dawn
我正在尝试将拉丁词放入一个字符串中,将英语等价词放入另一个字符串中。另外,每次我得到一个等效的英语时,我都希望能够将这两个字符串发送到我的函数。我的代码目前看起来像这样:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//#include "tree.h"
int main(int argc, char* argv[])
{
string latinWord = "",
englishWord = "";
char buffer;
bool isLatinWord = true;
ifstream vocabFile;
vocabFile.open(argv[1]);
if (!vocabFile)
cout << "File open failed." << endl;
while(vocabFile.get(buffer))
{
if (isLatinWord)
{
if (buffer == ':')
isLatinWord = false;
else
latinWord+= buffer;
}
else
{
if (buffer == ',') // indicates 1 of multiple equivs processed
{
cout << englishWord << " = " << latinWord << endl;
englishWord = "";
}
else if (buffer == '\n') // indicates all english equivs processed
{
cout << englishWord << " = " << latinWord << endl;
isLatinWord = true;
englishWord = latinWord = ""; // reset both strings
}
else
englishWord+= buffer;
}
}
}
这个应该起作用的方式是,如果有一个冒号,则表示拉丁单词字符串已完成填充(标志设置为 false),然后应该开始填充英文单词字符串。应该填充英文单词字符串,直到逗号被击中(此时将单词发送到函数)或换行符被击中(重置标志,因为此时已检查所有英文等效项)。
但是,当我尝试输出要发送到函数的字符串时,它们完全搞砸了。
这是我的输出:
$ ./prog5 latin.txt
= ac
= amo
= amor
= animal
= annus
before = ante
in front of = ante
= anteusly
= antiquus
burn = ardeo
be on fire = ardeo
= ardeo
arms = arma
= armas
= atque
= aurum
golden = aureus
= aureus
= aurora
[编辑] 这是我在 isLatinWord 标志修复后的输出。 我认为我的代码以错误的方式识别换行符,我想知道是否有人看到任何错误或有任何建议?
谢谢, 本
【问题讨论】:
-
一种可能更高级别的方法是读取文件中的每一行。然后根据“:”分隔符“拆分”每一行。我会首先创建一个函数来读取每一行,尽管 API 中可能已经有一个函数,然后我会编写另一个函数来分隔冒号处的行,尽管 API 中可能也已经有一个函数。
-
你第一次读到
buffer的单个字符。这是一个奇怪的设计,可能会解释一些问题。