이 프로그램은 사용자가 제공 한 텍스트 파일의 단락을 읽은 다음 각 행을 비정형 문자 배열에 저장하고 총 단어 및 줄 수를 계산해야합니다 그 다음 결과를 표시합니다.cstring 배열로 입력 된 단어와 줄을 어떻게 계산합니까?
왜 줄 수가 3 의 결과를 제공하고 왜 단어 수가 2 단어가 부족한 것인지 알 수 없습니다.
저는 전문가가 아니기 때문에 C++를 최근에 배우기 시작했음을 기억하십시오.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
ifstream infile;//declarations
char filename[45];
char **data = 0;
char **temp = 0;
char *str = 0;
char buffer[500], c;
int numoflines = 0, numofwords = 0;
cout << "Please enter filename: ";//prompt user to enter filename
cin >> filename;
infile.open(filename);//open file
if (!infile)//check if file was successfully opened
{
cout << "File was not successfully opened" << endl << endl;//display error message
return 0;
} //end of if
data = new char*[numoflines];
while (!infile.eof())
{
temp = new char*[numoflines + 1];
for (int i = 0; i < numoflines; i++)
{
infile.getline(buffer, 500);//read line
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
str = new char[strlen(buffer) + 1];//allocate a dynamic array
strcpy(str, buffer);
data[i] = str;
temp[i] = data[i];
}//end of for
infile.getline(buffer, 500);
for (int i = 0; i < strlen(buffer); i++)//count number of words in line
{
c = buffer[i];
if (isspace(c))
numofwords++;
}
temp[numoflines] = new char[strlen(buffer) + 1];
strcpy(temp[numoflines], buffer);
delete[] data;
data = temp;
numoflines++;
}
cout << "Number of words: " << numofwords << endl;
cout << "Number of lines: " << numoflines << endl;
return 0;
}
ifstream :: getLine'의 경우 기본 구분 기호는 '\ n'입니다. 나는 당신의 텍스트가 3 개의 단락을 포함하고 그것이 단지 3 '\ n'문자를 포함한다고 생각한다. 그래서 당신은 3을 줄 수만큼 얻는다. – sanastasiadis
단어의 수는 공백 문자를 확인하는 것이 문제라고 생각합니다. 어쩌면 공간 'OR'기간 '을 확인하십시오.' 더 좋을 것입니다. – sanastasiadis
"이 문자열"을 고려하십시오. 두 단어가 있지만 * 많은 * 공백이 있습니다. "이 문자열"도 고려하십시오. 두 단어와 단 하나의 공백이 있습니다. 마침내 "what-about-this"? 한 마디인가 세 마디인가? (오, 잊지 마세요 ""- 그것은 제로 단어입니다). –