【问题标题】:Program is reading in information from text file incorrectly, seemingly left to right, then right to left程序错误地从文本文件中读取信息,看似从左到右,然后从右到左
【发布时间】:2019-05-22 08:21:13
【问题描述】:

我正在尝试阅读有关 A. A 单词和 B. 所说单词的频率的信息。当函数读取信息时,第一个调用从左(字)到右(频率)读取它,然后下一个是从右(频率)到左(字)。我假设它是由于我的格式。我的假设是它的跳字。

dicFile << s.key << " " << s.wordCount << endl;

dicFile 是它被输出到的文本文件。 s.key 是单词,s.wordcount 是 int。

文本文件格式为:

会计 3

苹果 1

面包 1

....

读取
            fstream dictionaryFile;
            string dF, word, freq;
            cout << "Input dictionary file: ";
            cin >> dF;
            dictionaryFile.open(dF);
            if (dictionaryFile.is_open()) {
                while (dictionaryFile >> word) {
                    dictionaryFile >> word >> freq;
                    int frequ = stoi(freq);
                    newItem.key = word;
                    newItem.wordCount = frequ;
                    tree.AVL_Insert(newItem);
                }
            }
            else { cout << endl << "ERROR"; }

它在 atoi 崩溃,我假设是因为它无法处理“会计”。

【问题讨论】:

  • while (dictionaryFile &gt;&gt; word) { dictionaryFile &gt;&gt; word &gt;&gt; freq; -> 你读了两次word,然后读了freq。根据您的描述,这不是您打算执行的操作...(通过在调试器中逐步执行来检查这一点。观察wordfreqwhile 内的第一行之后出现的内容。)
  • 解决了,谢谢。
  • 恕我直言,正确的是while (dictionaryFile &gt;&gt; word &gt;&gt; freq) {,然后完全删除下一行。 (不客气。);-)
  • 您也可以考虑将freq 设为int 类型。这将使stoi() 过时。

标签: c++ fstream


【解决方案1】:

这是因为它无法处理“Apple”。

首先,while (dictionaryFile &gt;&gt; word) 读取“会计”,然后

dictionaryFile >> word >> freq;

将“3”读入word,将“Apple”读入freq

你应该做的是

while (dictionaryFile >> word >> freq) {
    int frequ = stoi(freq);
    // ...

或者您可以删除一堆变量改组并直接读入您的“项目”:

while (dictionaryFile >> newItem.key >> newItem.wordCount) {
    tree.AVL_Insert(newItem);
}

【讨论】:

    猜你喜欢
    • 2016-03-01
    • 2018-09-06
    • 2011-02-03
    • 2018-01-05
    • 2018-04-03
    • 2022-01-13
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多