我编写了一个代码来填充文件中的数组 然后使用该数组将其与用户输入进行比较 程序应该要求用户输入要在中搜索的名称或部分名称 排列 这是代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
bool found = false;
const int arraySize = 35;
const int length = 100;
char contacts[arraySize][length];
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
inputFile.open("input.txt"); // Open the file.
// Read the numbers from the file into the array.
// After this loop executes, the count variable will hold
// the number of values that were stored in the array.
while (count < arraySize && inputFile >> contacts[count])
count++;
// Close the file.
inputFile.close();
char search[length];
char *fileContact = nullptr;
int index;
cout << "To search for your contact's number \nplease enter a name or partial name of the person.\n";
cin.getline(search, length);
for (index = 0; index < arraySize; index++)
{
fileContact = strstr(contacts[index], search);
if (fileContact != nullptr)
{
cout << contacts[index] << endl;
found = true;
}
}
if (!found) cout << "Sorry, No matches were found!";
return 0;
}
并且文件中的名称是
“Alejandra Cruz,555-1223”
“Joe Looney,555-0097”
“Geri Palmer,555-8787”
“李晨,555-1212”“Holly Gaddis,555-8878”
“Sam Wiggins,555-0998”
“Bob Kain,555-8712”
“Tim Haynes,555-7676”
“Warren Gaddis,555-9037”
“Jean James,555-4939”
“Ron Palmer,555-2783”
所以代码有效,但问题是 当我写下亚历杭德拉时 输出是:“亚历杭德拉 输出应该显示全名和数字: “亚历杭德拉克鲁兹,555-1223”
有谁知道如何解决这个问题? 谢谢!!
答案 0 :(得分:1)
使用时
inputFile >> contacts[count]
contants[count]
。这解释了你的输出。
您需要改为使用istream::get
。
while (count < arraySize && inputFile.get(contacts[count], length) )
count++;
以上文件的所有行应该最多arraySize
行数。
您可以添加一些调试输出来解决问题。
while (count < arraySize && inputFile.get(contacts[count], length) )
{
std::cout << "Read " << count+1 << "-th line.\n" << "\t" << contants[count] << "\n";
count++;
}