0

当我从我的程序中读取一个包含 5 个单词的 .txt 文件并将其放入一个有 20 个空格的数组中时,我文件中的最后一个单词填满了我数组中的最后 16 个位置。任何想法为什么?我输入的文件最多有 20 个字。

newArray string[20];
if (inputFile) {
    while (i<20) {
        inputFile >> word;
        if (word.length()<2) {   //gets rid of single character words
            i++;
        }   
        else{
            newArray[i] = word;
            cout<<newArray[i]<< " ";
        }

    }
    inputFile.close();
}
4

2 回答 2

1

您的问题尚不清楚,但我确信在您的循环中您可能仍在添加最后一个词,因为您使用 while 循环的方式。添加完单词后,您并没有跳出循环。如果您在文件末尾,您应该跳出循环,这应该可以解决您最后一个单词出现多次的问题。

更好的方法是将整个文件读入 1 个字符串,并在数组中一次标记并添加每个单词。

如果这没有帮助,请提供完整的代码。另外我不明白你为什么有i++ }两次。这是一个错字吗?

希望这可以帮助。

编辑:试试这个代码:

int i = 0;
string line;
ifstream myfile("names.txt");
if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {
        arr[i] = line;
        i++;
    }
    myfile.close();
}

您不会在之后添加任何行

于 2016-01-17T04:05:55.230 回答
1

如果我错了,请纠正我,但为什么你需要一个包含 20 个字符串的数组来读取 5 个单词?下面的代码是将文件读入数组的标准方法。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
  string myArray[20];
  ifstream file("file.txt");
  string word;
  if(file.is_open())
    {
      int i = 0;
      while(file>>word)
        {
          if(word.length()<2)
            continue;
          else
            {
              myArray[i] = word;
              i++;
            }
        }
    }
}

附录:编辑将阅读所有单词并在没有更多文本时停止。您最初的问题是文件流在读取所有 5 个单词后没有读取任何内容,因此word保持不变,导致它填满数组。

于 2016-01-17T04:22:05.860 回答