发现自己对当前的项目有点困惑。我正在尝试将.txt文件(每个1行的空格分隔的名字和姓氏)读入数组。在阅读文件后,这是应该发生的事情。
我理解其中的大部分内容。该程序之前正在读取该文件,我甚至将其写出来显示即使它不是必需的。现在它只显示一个名称。寻找一些帮助让我再次活动。如果我对屁股感到痛苦或者我的代码被抬高了,请道歉。谢谢你的帮助。
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
//Function prototypes
void nameSort(string[], const int);
//prototype to display the contents of the file after sorting
//Although I do not need this I wanted to see the names were
//read in correctly.
void nameDisplay(string[], const int);
void nameSearch(string[], const int);
int index = 0; //loop counter
int main()
{
const int ARRAY_SIZE = 100;
string nameArray[ARRAY_SIZE];
//file object
ifstream fileIn;
fileIn.open("myFriends.dat");
while (index < ARRAY_SIZE && getline(fileIn, nameArray[index]))
index++;
//function call to sort the array
nameSort(nameArray, index);
//Display names to screen as a test of the sort
nameDisplay(nameArray, ARRAY_SIZE);
//function call for search
nameSearch(nameArray, ARRAY_SIZE);
system("pause");
return 0;
}
//function definitions
void nameSort(string *array, const int ARRAY_SIZE)
{
bool swap;
string temp;
do
{
swap = false;
for (int count = 1; count < (ARRAY_SIZE - 1); count++)
{
if(array[count-1] >array[count])
{
temp = array[count-1];
array[count-1] = array[count];
array[count] = temp;
swap = true;
}
}
}
while(swap);
}
void nameSearch(string *array, const int ARRAY_SIZE)
{
int first = 0;
int last = ARRAY_SIZE - 1;
int middle;
string name;
bool friends = false;
do
{
cout<<"Please enter a name or END to terminate:";
cin>>name;
}
while(!friends && first <= last && name != "END");
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
last = middle + 1;
}
}
void nameDisplay(string *array, const int ARRAY_SIZE)
{
for(int index = 0; index < ARRAY_SIZE; index++)
cout<<array[index]<<endl;
}
答案 0 :(得分:0)
您的姓名搜索似乎至少有一个错误。而不是:
while(!friends && first <= last && name != "END");
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
last = middle + 1;
}
应该有:
while(!friends && first <= last && name != "END");
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
first = middle + 1;
}