문자열에있는 단어의 수를 찾는 코드를 작성합니다. 각 단어를 다른 문자로 구분할 수 있음을 알고 있습니다. AZ (또는 az). 내가 작성한 코드는 문장의 시작 부분에 문장 부호가없는 경우에만 잘 작동합니다. 그러나 문제는 따옴표와 같이 구두점을 사용하여 문장을 시작할 때 발생합니다 (예 : "연결 만하십시오."는 결과가 2 대신 3 단어로 표시됨). 저는 Dev-C++을 사용하여 C++로 프로그래밍하고 있습니다. 귀하의 도움을 주시면 감사하겠습니다. 내 코드는 다음과 같습니다.문자열의 정확한 단어 수가 인용 부호와 같은 구두점으로 시작되지 않음
#include <cstring>
#include <iostream>
#include <conio.h>
#include <ctype.h>
using namespace std;
int getline(); //scope
int all_words(char prose[]); //scope
int main()
{
getline();
system ("Pause");
return 0;
}
int getline()
{
char prose[600];
cout << "Enter a sentence: ";
cin.getline (prose, 600);
all_words(prose);
return 0;
}
int all_words(char prose[])
{ int y, i=0, k=0; int count_words=0; char array_words[600], c;
do
{
y=prose[i++];
if (ispunct(y)) //skeep the punctuation
i++;
if ((y<65 && isspace(y)) || (y<65 && ispunct(y))) //Case where we meet spacial character or punctuation follwed by space
count_words++; //count words
if (ispunct(y)) //skeep the punctuation
i++;
}while (y); //till we have a character
cout <<endl<<" here is the number of words "<< count_words <<endl;
return 0;
}
***********************************Output******************************
Enter a sentence: "Only connect!"
here is the number of words 3
Press any key to continue . . .
답변 [1]을 (를) 당신의 질문에 답하십시오. [1] : http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c –