[英]How would I go about storing words from a plain text file to an array using C++?
I've been tasked with writing a C++ program that opens a text file, determines the length of each word, then produces output stating how many times a particular word length occurs.我的任务是编写一个 C++ 程序,该程序打开一个文本文件,确定每个单词的长度,然后生成 output 说明特定单词长度出现了多少次。
I've figured how to open and read the contents of the file.我已经想出了如何打开和读取文件的内容。
How would I take each word and store them in an array?我将如何获取每个单词并将它们存储在数组中?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void getFile(string);
void getFile(string filename)
{
string array[2];
short loop = 0;
string line;
ifstream myfile (filename);
if (myfile.is_open())
{
while (!myfile.eof() )
{
getline (myfile,line);
array[loop] = line;
cout << array[loop] << endl;
loop++;
}
myfile.close();
}
else{
cout << "can't open the file";
system("PAUSE");
}
}
int main(){
string fileName;
while (true){
cout << "\nEnter the name of a file: ";
getline(cin, fileName);
if (fileName == ""){
cout << "Invaled file name, enter another!!!"<<endl;
main();
}
else{
getFile(fileName);
}
}
return 0;
}
You do not store words in an array.您不会将单词存储在数组中。
You only need to store the word lengths and how often each of them occurred.您只需要存储单词长度以及每个单词出现的频率。
If you have a guaranteed and low maximum word length you can even simplify by using an array where the length of the current word is used as an index.如果您有一个保证且较低的最大字长,您甚至可以通过使用一个数组来简化,其中当前字的长度用作索引。 Init all entries with 0. Then count entries up when the corresponding word length occurs.用 0 初始化所有条目。然后在出现相应的字长时将条目计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.