我正在为基础编程课程开发一个项目,并不完全熟悉字符串等等。该程序的目标是获取一个带有一些随机,重复单词的简单文本文件,并返回一个文件,其中包含每个单独的单词以及它在文件中出现的次数。输入文件类似于
Class
Text
Class
fall
mark
mark
Text
输出应该是
Class 2
Text 2
fall 1
mark 2
我无法读取和设置输入数据的数组。不确定如何设置它。任何建议都会很棒。
int main(void)
{
int k=0, p=0, words=0, match=0, ch=0;
double xx;
char I[WORD][LETTER;
FILE *file;
file = fopen("C:\\Users\\Andrew\\Documents\\te2.txt", "r");
if(file != NULL){
// Count the amount of words in file set up array
int i=0, j=0;
for(i=0; i<WORD; i++){
for(j=0; j<LETTER; j++){
fscanf(file, "%s", &I[i][j]);
ch++;
}}
答案 0 :(得分:0)
你要做的事情非常简单。让我们分解一下:
std::map
)。让我们逐字阅读文件。搜索read in a file word by word c++已经足够了,但这是一个简短的例子:
ifstream file; // A in file stream, the c++ way of reading files.
file.open ("example.txt");
string word; // A word to store each word.
// Read each word.
while ( file >> word) {
// Do something with your word. (Part 2)
}
就这么简单!
现在我们想要一张地图,这是因为地图只会存储唯一的单词,我们可以使用它的值来计算每个唯一单词的数量。阅读地图here。我们需要一个字符串作为键和一个int来计算单词,所以:
std::map<std::string, int> myWords;
要将它们放入,我们需要检查该单词是否已存在,否则我们将其设置为:
// See if the map already contains the word (not only is this easy, it is also very efficient!)
// If we dont contain the word then we get an iterator to past the end of the map.
if (myWords.find(word) == myWords.end()) {
myWords[word] = 1; // If our map doesn't already have this word
// we have encountered our first!
} else {
myWords[word]++; // The map already has the word so just increment it.
}
简单的部分,只需遍历地图并将其打印出来:
for (auto wordPair : myWords) {
std::cout << wordPair.first << " " << wordPair.second << std::endl;
}
你明白了:
答案 1 :(得分:0)
所以我一直在研究它,我想出了让数据按字符fscanf(file, "%c", &array[]);
逐字逐句的想法,我一直在研究一种算法来设置一定数量的字符。 &#39; \ n&#39;进入一个较小的数组,使用它与完整的字符串进行比较。在文件中,我已经为任何单词添加了空格,这些单词的大小与空格完全相同,数组成功只是算法本身存在一些问题。
`
#include <stdio.h>
#include <cctype>
#define Words 9
#define Letters 6
#define CHARACT Words*Letters
#define CORRECT 3
int main(void){
double xx;
int match=0, indx=0, i=0, k=0, j=0, b, read=0, r, t, track=0;
char shrt[Letters], Long[CHARACT], c;
FILE *file;
file =fopen("C:\\Users\\Andrew\\Documents\\te2.txt", "r");
if(file != NULL)
{
// initialize long string (full file by characters)
for(k=0; k<CHARACT; k++)
{
fscanf(file, "%c", &Long[k]);
}
// set up shrt[] to compare to rest of array
while(track <= CHARACT)
{
indx+=track;
//STEP 1: take shrt[] out of Long[] for comparisons
for(r=0; r<Letters; r++)
{
shrt[r] = Long[indx];
indx++;
if(shrt[r] == '\n')
break;
}
for(t=0; t<CHARACT; t++)
{
match=0;
int VV = track*Letters;
// STEP 2: keep shrt[] constant, compare to full string one by one
for(int p=0; p<Letters-2; p++)
{
if(shrt[p] == Long[VV])
{
match++;
}
}
if(match >= CORRECT)
{
for(int ee=0; ee<Letters; ee++)
{
printf("%c", shrt[ee]);
}
printf(" %i", match);
}
track+=Letters;
}
}// big for loop
// TESTING TESTING
printf("\n\n\nTEST\n\n");
for(k=0; k<CHARACT; k++)
printf("%c", Long[k]); // delete when ready
printf("%i", read);
}// big if
else{
printf("error");
}
fclose(file);
scanf("%f", &xx);
return 0;
}`