2011-11-03 2 views
0

이 프로그램을 살펴보면서 숫자 대신 배열에서 문자를 검색하는 방법을 알아 내려고 시도했지만, 숫자에 대해서는 작동하지만 어떻게 문자로 작동시킬 수 있습니까? 제발 도와주세요 ............... 코드는 여기배열을 검색하는 방법

#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; 
} 
+0

정확히 어떤 도움을 받아야합니까? 어떤 오류 메시지가 나타 납니까? –

+4

Yikes. 안구 경보! 공백, 들여 쓰기, 서식 및 미적 감각을 사용해보십시오! –

+1

숙제입니까? Anders K.가 말했듯이, 당신은 무엇을 시도 했습니까? 사람들은 질문에 답하고 코드는 쓰지 않습니다. – Tony

답변

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; 
} 
} 
+0

로컬 변수를'char'으로 변경했지만 함수에 전달 된 배열 타입을 변경하지 않았습니다. 사용되지 않은 인수'string & letter '도 있지만 원래 코드에있었습니다. – Tony

+0

원본 코드에 필요한 변경을 최소화하려고했지만 좋은 지적이 있습니다. char가 int로 저장 될 수 있지만 char 배열을 사용하여 작업중인 내용을 명확하게해야합니다. –

관련 문제