我的代码中唯一有问题的部分是将具有最多2000行数据的字符串与具有1条数据(用户输入)的字符串进行比较的部分。我添加了else语句以表明if语句永远不会为真。我的老师无法弄清楚为什么它将评估为假。谁能告诉我为什么该陈述总是错误的,以及如何解决?
//
// main.cpp
// Assignment 5
//
//
#include <iostream>
#include <string>
#include <stdlib.h>
#include <iomanip>
#include <fstream>//for fin and fout
#include <string>
using namespace std;
int main()
{
//declare input and output file stream
ifstream fin;//in_s, inStream, input...
string name[2000], inName;//name is the string for the file, inName is the users name
string number[2000];
char again;
cout << "Welcome to the automated phone directory! " << endl << endl;
//Open the file streams and associate with the actual files
fin.open("/Users/ryoncook/Documents/School/Comp Sci/Assignments/Assignment 5/Asn Five_M/phoneNames.txt");
if (fin.fail())
{
cout << "Input file opening failed" << endl;
exit(1);//indicates 1 error occured
}
for(int i=0; i < 2000; i++)//loops until desired maximum size
{
getline(fin,name[i]);//stores the values of the file in the string array
}
fin.close();
//open number file
fin.open("/Users/ryoncook/Documents/School/Comp Sci/Assignments/Assignment 5/Asn Five_M/phoneNums.txt");
if (fin.fail())
{
cout << "Input file opening failed" << endl;
exit(1);//indicates 1 error occured
}
for(int i=0; i < 2000; i++)//loops until desired maximum size
{
getline(fin,number[i]);//stores the values of the file in the string array
}
//Close all open files
fin.close();
do{
cout << "Enter the name of the person you wish to look up: " << endl;
inName.clear();
getline(cin,inName);//reads the name desired as a string
for (int i=0; i < 2000; i++)
{
if (name[i] == inName)//compares input name with file name
{
cout << name[i] << "'s phone number is " << number[i] << endl;//prints result
}
else
{
cout << name[i] << inName;//i ran an else statement to confirm. The out if statement is never evaluated to be true
}
}
cout << "Would you like to find another phone number? (Y or N) " << endl;
cin >> again;
}while (again=='y' || again=='Y');
return 0;
}
//array for phone numbers and array for names that are both strings
//compare the 2 arrays and if they are equal, print
for循环应找到用户输入的名称,如果在文件中,则应选择正确的名称和电话号码。 实际上发生的是,即使输入的名称在文件中,该语句也永远不会为真。
我知道if语句是问题所在,因为我打印了一些具有不同数字(例如number [12],name [6]等)的名称和数字字符串,并且它们都打印了正确的名称/数字