如何在数组中搜索字母

时间:2011-11-03 21:35:15

标签: c++

正在查看这个程序,我试图找出如何搜索数组中的字母而不是数字,它适用于数字,但我怎样才能使它适用于字母。请帮助...............这是代码

#include <iostream>
using namespace std;
const int DECLARED_SIZE = 4;

void fillArray(int a[], int size, string& letter);
int search(const int a[], string letter, string target);

int main( )
{
    int arr[DECLARED_SIZE]; string listletter; string target;
    fillArray(arr, DECLARED_SIZE, listletter);
    char ans;
    int result;
    do
    {
        cout << "Enter a letter to search for: ";
        cin >> target;
        result = search(arr, listletter, target);
        if (result == -1)
            cout << target << " is not on the list.\n";
        else
            cout << target << " is stored in array position "
            << result << endl
            << "(Remember: The first position is 0.)\n";
        cout << "Search again?(y/n followed by Return): ";
        cin >> ans;
    } while ((ans != 'n') && (ans != 'N'));
    cout << "End of program.\n";
    return 0;
}

void fillArray(int a[], int size, string& letter)
{
    cout << "Enter up to " << size << " letter.\n"
        << "Mark the end of the list with a negative number.\n";
    int next, index = 0;
    cin >> next;
    while ((next >= 0) && (index < size))
    {
        a[index] = next;
        index++;
        cin >> next;
    }
}

int search(const int a[], string numberUsed, string target)
{
    int index  = 0; 
    string run = "run";
    bool found = false;

    while ((!found)) // && (index < numberUsed))
        if (target == run)
            found = true;
        else
            index++;

    if (found)
        return index;
    else
        return -1;
}

1 个答案:

答案 0 :(得分:0)

我注意到你在fillArray中加载一个int。如果你想要输入字符,你需要使用char。

void fillArray(int a[], int size, string& letter)
{
 cout << "Enter up to " << size << " letter.\n"
 << "Mark the end of the list with a negative number.\n";
 char next;
 int index = 0;
 cin >> next;
 while ((next >= 0) && (index < size))
 {
   a[index] = next;
   index++;
 cin >> next;
 }
}