基本上我的计划目标是我有一个包含4个电话号码的文件 它看起来像这样
Harry Keeling (555)123-4567
Frank James (555)123-8901
Arthur Paul (555)987-4567
Todd Shurn (555)987-8901
我的程序现在正在做的是提示用户输入姓名和姓名,并遍历文件以查看他们是否匹配如果匹配则电话号码保存在可变电话号码中(如果他们不是一个匹配的程序输出错误现在我的程序正在做什么是暂停做但但是在找到每个匹配后程序被暂停以提示你想要继续查找数字y或n如果它是肯定它是暂停循环通过文件再次,但基本上我的程序不工作,我不知道为什么我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lookup_name(ifstream&, string&); // prototype
int main()
{
ifstream myfile;
string phonenumber;
string choice;
lookup_name(myfile, phonenumber);
if (phonenumber == " ") {
cout << "Error" << endl;
}
else {
cout << "The Telephone Number you Requested is" << phonenumber << endl;
cout << "Do you Want to look up another name in the directory?" << " " << "<Y/N" << endl;
cin >> choice;
if (choice == "Y")
lookup_name(myfile, phonenumber);
}
}
void lookup_name(ifstream& myfile, string& phonenumber)
{
string fname;
string lname;
string name1, name2, dummy, choice;
myfile.open("infile.txt");
cout << "What is your first name" << endl;
cin >> fname;
cout << "What is your last name" << endl;
cin >> lname;
for (int i = 0; i < 4; i++) {
myfile >> name1 >> name2;
if (fname + lname == name1 + name2) {
myfile >> phonenumber;
myfile.close();
if (choice == "Y")
{
continue;
}
else {
myfile >> dummy;
}
}
}
}
答案 0 :(得分:1)
您需要在main()
内部添加一个循环以提示用户继续,并且您需要修复lookup_name()
函数中的错误。
尝试更像这样的东西:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <limits>
using namespace std;
bool lookup_name(istream&, const string&, string&); // prototype
int main()
{
ifstream myfile("infile.txt");
string name, phonenumber, choice;
do
{
cout << "What is the name? ";
getline(cin, name);
if (!lookup_name(myfile, name, phonenumber)) {
cout << "Error" << endl;
}
else {
cout << "The Telephone Number you Requested is '" << phonenumber << "'" << endl;
}
cout << "Do you want to look up another name in the directory (Y/N)? ";
cin >> choice;
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
if ((choice != "Y") && (choice != "y"))
break;
myfile.seekg(0);
}
while (true);
return 0;
}
bool lookup_name(istream& myfile, const string& name, string& phonenumber)
{
string line, fname, lname;
while (getline(myfile, line))
{
istringstream iss(line);
if (iss >> fname1 >> lname)
{
if (name == (fname + " " + lname))
return getline(iss, phonenumber);
}
}
return false;
}