【问题标题】:How Do I allow a user search for contents in a file in C?如何允许用户在 C 中搜索文件中的内容?
【发布时间】:2013-04-12 13:48:16
【问题描述】:

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

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;
            }

【问题讨论】:

  • 嗯,是的,我没有看到任何与输入的内容进行比较...
  • 我尝试了另一种可行的方法。一会儿我会发在这里

标签: c++ arrays string search


【解决方案1】:

为什么会有 for 循环?做这样的事情会不会更容易:

 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";
 }

我没有测试过这段代码,但希望它能让你知道应该走哪条路。

【讨论】:

猜你喜欢
  • 2015-02-15
  • 1970-01-01
  • 2021-06-07
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
相关资源
最近更新 更多