2013-02-11 39 views
0

我不能为了我的生活找出为什么这不起作用。我不得不对文件中的单词列表进行频率检查,并且在读取它们时,我试图检查当前单词是否与字符串数组中的元素相对应,并确保它们在我之前不等于添加它。代码如下:检查从文件读入数组中的字符串

fin.open(finFile, fstream::in); 

if(fin.is_open()) { 
    int wordArrSize; 
    while(!fin.eof()) { 
     char buffer[49]; //Max number chars of any given word in the file 
     wordArrSize = words.length(); 

     fin >> buffer; 

     if(wordArrSize == 0) words.push_back(buffer); 

     for(int i = 0; i < wordArrSize; i++) { //Check the read-in word against the array 
      if(strcmp(words.at(i), buffer) != 0) { //If not equal, add to array 
       words.push_back(buffer); 
       break; 
      } 
     } 



     totNumWords++; //Keeps track of the total number of words in the file 
    } 
    fin.close(); 

这是一个学校项目。我们不允许使用任何容器类,所以我构建了一个结构来处理扩展char **数组,推回和弹出元素等。

+2

@Alex,为什么地球上不应该问作业问题? – SingerOfTheFall 2013-02-11 07:25:49

+0

@SingerOfTheFall我认为他们被禁止? – 2013-02-11 07:36:11

+1

@Alex,不,我们只是不再用[tag:作业]标记问题。作业问题与其他任何问题没有区别。你可以在[tag:homework]标签info – SingerOfTheFall 2013-02-11 07:40:02

回答

1
for(int i = 0; i < wordArrSize; i++) { //this part is just fine 
    if(strcmp(words.at(i), buffer) != 0) { //here lies the problem 
     words.push_back(buffer); 
     break; 
    } 
} 

你将进入你的if声明每次当前字不匹配数组中的第i个字。所以,大多数时候,这将是您进入循环的第一次迭代。这意味着在循环开始时(在字符串列表中与缓冲区不匹配的第一个单词),您将缓冲区添加到字符串列表并打破循环。

你应该做的是完成检查整个words数组,然后将缓冲区添加到数组中。所以你应该有这样的事情:

bool bufferIsInTheArray = false;//assume that the buffered word is not in the array. 
for(int i = 0; i < wordArrSize; i++) { 
    if(strcmp(words.at(i), buffer) == 0) { 
     //if we found a MATCH, we set the flag to true 
     //and break the cycle (because since we found a match already 
     //there is no point to continue checking) 
     bufferIsInTheArray = true; 
     break; 
    } 
//if the flag is false here, that means we did not find a match in the array, and 
//should add the buffer to it. 
if(bufferIsInTheArray == false) 
    words.push_back(buffer); 
} 
+0

这样做了,谢谢!我不知道为什么这件事早些时候没有提到。看起来像我的逻辑起初是充分证明的 – 2013-02-11 07:53:25

1

我认为您的代码words.push_back(buffer);应该超出for循环。 将一个标志来检查,如果你发现在for循环数组缓冲区,并根据标志其添加到阵列外的for循环

+0

试过了,没有去。 这与strcmp()取得两个char *无关?除非我错过了某些东西,否则缓冲区[49]在传递时应该衰减为指针。真的没有其他的解释...这个检查应该被切断和干燥argh – 2013-02-11 07:35:59

+0

你确定。我修改的意思是在上面的答案中正确编码你是否尝试过这个答案。在你的代码中,如果任何一个单词与单词中的单词不同,那么它会添加到数组中 – 999k 2013-02-11 07:43:08

+0

@TaylorBishop它确实会衰减到一个指针。 – 2013-02-11 07:44:45