如何使用文件填充数组并将其与用户输入C 进行比较

how do I use a file to populate the array and compare it with user input c++

本文关键字:输入 用户 比较 文件 何使用 填充 数组      更新时间:2023-10-16

我编写了一个代码来填充文件的数组然后使用该数组将其与用户输入进行比较该程序应要求用户输入一个名称或部分名称以在大批这是代码:

#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"

"让·詹姆斯,555-4939"

"罗恩·帕尔默(Ron Palmer(,555-2783"

所以代码有效,但是问题是例如,当我写亚历杭德拉(Alejandra(输出是:"亚历杭德拉输出应该显示全名和数字:"亚历杭德拉·克鲁兹(Alejandra Cruz(,555-1223"

有人知道如何解决这个问题吗?谢谢!!

当您使用

inputFile >> contacts[count]
  1. 丢弃了领先的空格字符。
  2. 非空格字符被读为contants[count]
  3. 当遇到空格字符时,阅读会停止。

解释您的输出。

您需要改用istream::get

while (count < arraySize && inputFile.get(contacts[count], length) )
    count++;

回应OP的评论

以上应将文件的所有行高到arraySize行数。

您可以添加一些调试输出来解决问题。

while (count < arraySize && inputFile.get(contacts[count], length) )
{
    std::cout << "Read " << count+1 << "-th line.n" << "t" << contants[count] << "n";
    count++;
}