简体   繁体   中英

Reading words from a text file C++ (weird characters)

firstword secondword thirdword fourthword ...

My text file contains 200 words like this order and I want to read and copy them into a 2D fixed length of array, without weird characters. I couldn't be able to perform this operation with this piece of code:

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];
            }
        }
    }

How can I do this?

You need to add '\\0' at the end of the word so there won't be any wierd characters if the length of the word is less than LEN .

However I recommend using vector of strings for the job.

#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;
}

Think about this:

FRUITS >> fruits1[c];

But you have to be sure that LEN is sufficient to hold all the char in each word plus the '\\0' .

And don't worry about the "=+½$#". When you do thing like cout << fruits1[c]; they don't get printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM