我在此程序上遇到了麻烦,该程序需要在数组中搜索用户输入的字符串,然后打印出与匹配字符串匹配的整行。目前,这仅部分起作用,因为只有在存在匹配项时才打印出字符串,而不是字符串所在的整个行。这是带有数据的文本文件。
Murray Jones, 555-1212
Christal Delamater, 555-4587
Zetta Smith, 555-6358
Elia Roy, 555-5841
Delmer Bibb, 555-7444
Smith Nevers, 555-7855
Roselle Gose, 555-3211
Jonathan Basnett, 555-5422
Marcel Earwood, 555-4112
Marina Newton, 555-1212
Magdalen Stephan, 555-3255
Deane Newton, 555-6988
Mariana Smith, 555-7855
Darby Froman, 555-2222
Shonda Kyzer, 555-3333
Jones Netto, 555-1477
Bibone Magnani, 555-4521
Laurena Stiverson, 555-7811
Elouise Muir, 555-9633
Rene Bibb, 555-3255
这是我到目前为止的代码。如果您能帮助我,我将不胜感激!
void searchArray(string array[], int size)
{
string userInput;
bool found = false;
cout << "Enter a name to search the data: " << endl;
cin >> userInput;
for (int i = 0; i < size; i++)
{
if (userInput == array[i])
{
found = true;
cout << endl;
cout << "Matching Names: " << endl;
cout << array[i] << endl;
}
}
}
这是main(),它读取文件并将每一行放入数组中。
int main()
{
ifstream infile;
infile.open("Data.txt");
int numOfEntries = 0;
string nameAndNumber, line;
string *namesAndNumbers = nullptr;
if (!infile)
{
cout << "Error opening file.";
return 0;
}
else
{
while (getline(infile, line))
{
numOfEntries++;
}
namesAndNumbers = new string[numOfEntries];
infile.clear();
infile.seekg(0, ios::beg);
int i = 0;
while (getline(infile, line))
{
stringstream ss(line);
ss >> nameAndNumber;
namesAndNumbers[i] = nameAndNumber;
i++;
}
}
cout << "The number of entries in the file is: " << numOfEntries << endl << endl;
searchArray(namesAndNumbers, numOfEntries);
delete[] namesAndNumbers;
return 0;
}
最佳答案
我建议您对输入进行建模。将每一行视为记录或结构:
struct Record
{
std::string name;
std::string phone;
};
下一步是使
operator>>
重载以读取记录:struct Record
{
friend std::istream& operator>>(std::istream& input, Record& r);
std::string name;
std::string phone;
};
std::istream& operator>>(std::istream& input, Record& r)
{
std::getline(input, name, ','); // The ',' is not put in the string.
std::getline(input, phone);
return input;
}
上面的代码使您可以有一个简单的输入循环:
std::vector<Record> database;
Record r;
while (input_file >> r)
{
database.push_back(r);
}
要查找与姓名关联的电话号码,可以搜索数据库:
size_t db_index = 0;
const size_t quantity = database.size();
for (db_index = 0; db_index < quantity; ++db_index)
{
if (database[index].person == name_to_search)
{
Do_Something(index);
break;
}
}
还有其他选择,具体取决于您如何使用数据库。例如,如果仅按名称或电话搜索,则可以使用
std::map
。您还可以为姓名和电话创建索引表,因此不必在每次搜索之前对数据库进行排序。关于c++ - 在字符串数组中搜索用户输入的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48999139/