gpt4 book ai didi

c++ - 如何确定名称和 lname 是否不在文件中

转载 作者:行者123 更新时间:2023-11-28 05:14:08 25 4
gpt4 key购买 nike

该程序基本上是用来迭代包含元素的文件

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

如果名字和姓氏存在于文件中,我当前的程序正在输出电话号码,但如果它不是我当前的代码,我如何输出电话号码。

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

最佳答案

只返回你是否从查找函数中找到它

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

关于c++ - 如何确定名称和 lname 是否不在文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42991955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com