【发布时间】:2018-08-06 12:53:37
【问题描述】:
我在使用这个程序时遇到了一些问题,它需要在数组中搜索用户输入的字符串,然后用匹配的字符串打印整行。目前,这只是部分工作,因为只有在匹配时才打印出字符串,而不是字符串所在的整行。这是包含数据的文本文件。
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;
}
【问题讨论】:
-
请使用读取输入文件的代码更新您的帖子。
-
好的,我已经更新了原帖。
-
ss >> nameAndNumber;stringstream 定界符是空格。在输入文件中,每个条目的逗号后面都有一个空格。所以它会错误地标记输入。
-
有趣。解决此问题的最佳方法是什么?只是不使用字符串流或其他东西?
-
不确定您的意图。如果您追求名称到数字的映射,则可以使用字符串流来获取标记并将其存储在 map
(或 multimap 或类似结构)中。 [注意:每行您将获得两个令牌。]。 stackoverflow.com/questions/236129/…
标签: c++