0
문자열 하나를 문자와 비교하는 데 문제가 있으며 문자열에 몇 개의 문자가 있는지 계산합니다. 문자 "z"가 "z"와 일치하지만 "z"가 "Z"와 일치하지 않는 경우와 같이 대소 문자 만 비교하면됩니다.포인터를 사용하여 텍스트의 문자를 단일 문자와 비교
/**********************************************************************
* compares the letter to each letter in the string of text and counts the
* number of the matching letters
***********************************************************************/
int countLetters(char letter, char * text)
{
int count = 0;
for (char * p = text; *p; p++)
{
if (letter == *p)
{
count++;
}
}
return count;
}
/**********************************************************************
* Prompts the user for a line of input, calls countLetters(), and displays
* the number of letters.
***********************************************************************/
int main()
{
char letter;
char text;
int count = 0;
char * pText;
cout << "Enter a letter: ";
cin >> letter;
cout << "Enter text: ";
cin.ignore(2);
cin >> text;
pText = &text;
count = countLetters(letter, pText);
cout << "Number of '" << letter << "'s: " << count << endl;
return 0;
}
이 내가 코드를 실행할 때 보이는 방법은 다음과 같습니다 : 여기에 지금까지 무엇을 가지고 것은
Enter a letter: z
Enter text: There are no Z's here
Number of 'z's: 0
:
Enter a letter: z
Enter text: There are no Z's here
Number of 'z's: 1
이 내가 코드를 실행할 때 발생하는 기대입니다
아이디어가 있으십니까? 어떤 도움이라도 대단히 감사 할 것입니다.
'text'를 배열로 선언하려면 "char text [256]"? 이 변경을하면 컴파일러에서 "char (*) [256] '을'char * '로 변환 할 수 없다는 오류가 발생합니다. 이 인스턴스에서 '텍스트'를 배열로 올바르게 선언하려면 어떻게해야합니까? – starkiller
@starkiller'std :: string' 또는 적어도'std :: vector'를 사용하는 것이 좋습니다. –
@starkiller; 배열 변경을위한 공간을 할당 한 후'pText = &text;'를'pText = text;'에 저장합니다. – haccks