0

我有一个包含不同联系人详细信息的文本文件。基本上是这样的

John Doe 024587 7 月 24 日在家工作 在家生活 Jane Doe 024584 8 月 25 日在工作中工作 生活在工作中

我希望能够在文件中搜索“John Doe”或“Jane Doe”。

我决定从文件中读取内容并将它们存储在一个数组中。我想知道如何搜索数组。这段代码似乎没有削减它。noOfContacts 是文件中的联系人数量。

          readFile.open("book.txt", ios::out);
          while (!readFile.eof())
          {
            cout << "Enter anything you wish to search" <<endl;
            getline(cin, searchString);

            for (int k = 0; k < noOfContacts; k++)
            {       
                        getline (readFile,name[k]);
                                readFile >> phone[k];
                getline(readFile,birth[k]);
                getline(readFile,address[k]);
                getline(readFile,workplace[k]);


                cout << name[k]<<endl;
                cout << phone[k]<< endl;
                cout << birth[k]<<endl;
                cout << address[k]<<endl;
                cout << workplace[k]<<endl;


                break;
            }
4

1 回答 1

0

Why is there a for loop? Would it not be easier to do something like:

 unsigned found = 0;

 cout << "Enter anything you wish to search" <<endl;
        getline(cin, searchString);

 while(!readFile.eof() && (found==0)){  
     getline(readFile,testString);

     found=testString.find(searchString);
 }

 if (found == 0) {
 cout << "String found!\n " << testString.c_str(); << endl;
 }
 else{
 cout << "String Not Found!\n";
 }

I've not tested this code but hopefully it'll give you an idea of which way to go.

于 2013-04-12T14:02:31.420 回答