0
firstword secondword thirdword fourthword ...

我的文本文件包含 200 个像这个顺序一样的单词,我想读取它们并将它们复制到一个 2D 固定长度的数组中,没有奇怪的字符。我无法使用这段代码执行此操作:

ifstream FRUITS;
FRUITS.open("FRUITS.TXT");


    if(FRUITS.is_open())
    {
        char fruits1[200][LEN];
        int c;

        for(c = 0; c < 200; c++)
        {
            char* word;
            word = new char[LEN];

            FRUITS >> word;

            for(int i = 0; i < LEN; i++)
            {
                fruits1[c][i] = word[i];
            }
        }
    }

我怎样才能做到这一点?

4

2 回答 2

0

您需要'\0'在单词的末尾添加,这样如果单词的长度小于LEN.

但是,我建议使用字符串向量来完成这项工作。

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

using namespace std;
int main()
{
    fstream file;
    vector<string> v;
    file.open("FRUITS.txt");
    string tmp;
    while(!file.eof())
    {
        file >> tmp;
        v.push_back(tmp);
    }
    for(vector<string>::iterator i=v.begin(); i!=v.end(); i++)
    {
        cout << *i << endl;
    }
    file.close();
    return 0;
}
于 2013-03-26T23:05:58.390 回答
0

想一想:

FRUITS >> fruits1[c];

但是您必须确保LEN足以容纳char每个单词中的所有'\0'.

并且不要担心"=+½$#".当你做的事情就像cout << fruits1[c];他们没有被打印出来一样。

于 2013-03-26T23:07:51.543 回答