How do I reset a while loop?

天大地大妈咪最大 提交于 2019-12-12 03:05:20

问题


Here is an extract for some code that I am working on. Just wondering how would I go about resetting the nested loop? It remains at the end of the file when the first loop runs again.

while(fscanf(fp2,"%s", wordcheck)!=EOF)//Reads word from text file into array//
    {

        for (i=0; wordcheck[i]; i++)
        {
            wordcheck[i] = tolower(wordcheck[i]);//makes all characters lower case//
        }

        printf("%s", wordcheck);

        while(fscanf(fp1,"%s", worddict))
        {   
            if(strcmp(wordcheck, worddict)==0)//compare strings//
            {
            printf("This word: %s is in the dictionary\n", wordcheck);
            dictcount++;
            break;
            }

            else
            {
            dictcount++;
            }

            if(worddict == NULL)
            {
            printf("Your word: %s is not in the dictionary\n", wordcheck);
            }
        }
    }

回答1:


Use fseek:

fseek(fp2, 0, SEEK_SET);

.. or more simply, rewind:

rewind(fp2);



回答2:


The easiest way is to rewind() the stream, with a simple

rewind(fp2);

This is what you need, since it's not "the loop" that needs to be reset. The loop is just iterating over the lines of an input file, and the loop itself cannot be "restarted" without somehow changing the state of the file. Luckily, that's just what rewind() does, since it resets the file to be as it was just after you opened it.

As others have pointed out, this is a very inefficient way of validating text against a dictionary, since the file-based iterating is repeated for every word of input to be checked. Files are not particularly fast, especially not compared to data in memory. So, it would probably be a huge win if you do this for big sets of input to build some kind of in-memory dictionary based on the file input.

This could be very simple, I would recommend starting out with an array of words which you first sort (with qsort()) and then search using binary search (available in the bsearch() standard library function). When building the initial array, you will want to use realloc() to grow it dynamically, since you can't know when you open the dictionary file how many words it contains.




回答3:


You need to reset the file pointer. However, this is quite inefficient. It would be better to look for the words in some kind of index. If the dictionary can fit into memory, you could use a hash table or a trie (or even a simple binary search tree) to make the loop much faster. If the dictionary is too large to fit in memory you could still use more efficient search in a file based on a binary search.



来源:https://stackoverflow.com/questions/8576785/how-do-i-reset-a-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!