从一个c++文本文件中读取单词(奇怪的字符)

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

本文关键字:单词 读取 字符 文本 一个 c++ 文件      更新时间:2023-10-16
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];
            }
        }
    }

我该怎么做?

您需要在单词的末尾添加'',这样如果单词的长度小于LEN,就不会有任何奇怪的字符。

但是我推荐使用vector of strings。

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

考虑一下:

FRUITS >> fruits1[c];

但是你必须确保LEN足以容纳每个单词中的所有char加上''

不要担心"=+½$#".当你做像cout << fruits1[c];这样的事情时,它们不会被打印出来

相关文章: