从一个c++文本文件中读取单词(奇怪的字符)
Reading words from a text file C++ (weird characters)
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];
这样的事情时,它们不会被打印出来
相关文章:
- 从字符串变量中逐字符读取单词
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 如何从文件中读取单词,将它们分配给数组并分析其内容?
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- 我需要C++读取字符串数组中每个单词的第一个字母
- 如何读取文件的内容,如果文件中的单词重复,请将它们添加到列表中?
- 如何读取特定单词之间的文本文件?
- 无法读取文本文件中的每个单词
- C 读单词读取文件,而没有任何符号
- C :按行读取txt文件的读数,单词用单词读取,每行的单词不均匀
- 从文件重载运算符>>读取单词
- 尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C
- 读取每个单词的文件,并使用二叉搜索树(词典)对这些单词进行排序
- 如何在文本文件中仅读取一行,该文本文件使用QT具有特定单词
- 动态分配的数组C 读取句子并打印单词
- C++ 输出在读取文本文件时跳过最后一个单词
- 按 int 读取文件,然后按单词读取
- 用相同的前一个单词和相同的后一个单词读取不同的QString?QString::indexOf
- c++将文本文件中的两个单词读取到单个字符数组中