如何确定name和lname是否不在文件中

时间:2017-03-24 05:22:54

标签: c++

该程序基本上可以迭代包含元素的文件

Harry Keeling (202)806-4830
Frank James (301)123-3459
Arthur Paul (202)865-9090
Todd Shurn (410)560-8909
Richard Okpala 202 388 410

如果我的当前程序正在输出phonenumber,如果firstname和lastname存在于文件中,但如果它不知道我输出的电话号码不是我当前的代码。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lookup_name(ifstream&, string&, string&, string&);  // prototype
int main()
{
    ifstream myfile;
    string name, lastname, phonenumber;

    char choice;


    do
    {
        myfile.open("infile.txt");
        cout << "What is the First name? " << endl;
        cin >> name;
        cout << "what is your last name?" << endl;

        cin >> lastname;
        lookup_name(myfile, name, lastname, phonenumber);

        cout << "Do you want to lookup another name<Y/N" << endl;
        cin >> choice;


    } while (choice == 'Y');
    return 0;
}
void lookup_name(ifstream& myfile, string& name, string& lastname, string& phonenumber)
{
    string name1, name2, fullname, secondname, dummy;
    for (int i = 0; i < 5; i++) {
        myfile >> name1 >> name2;
        fullname = name1 + name2;
        secondname = name + lastname;
        if (fullname == secondname) {
            myfile >> phonenumber;
            cout << phonenumber << endl;
            myfile.close();
            break;
        }
        else if (fullname != secondname) {
            myfile >> dummy;
            phonenumber = dummy;
        }

1 个答案:

答案 0 :(得分:1)

只需返回您是否从查找功能中找到它

int lookup_name(ifstream& myfile, string& name, string& lastname, string& phonenumber)
{
    string name1, name2, fullname, secondname, dummy;
    for (int i = 0; i < 5; i++) {
        myfile >> name1 >> name2;
        fullname = name1 + name2;
        secondname = name + lastname;
        if (fullname == secondname) {
            myfile >> phonenumber;
            cout << phonenumber << endl;
            myfile.close();
            return 1;
        }
        else if (fullname != secondname) {
            myfile >> dummy;
            phonenumber = dummy;
        }
   }
 return 0;
}

然后使用返回值

if ( ! lookup_name(myfile, name, lastname, phonenumber) ) {
   cout << "Nope, didn't find it!" << endl;
}