2016-11-11 5 views
-1

이 프로그램은 사용자가 제공 한 텍스트 파일의 단락을 읽은 다음 각 행을 비정형 문자 배열에 저장하고 총 단어 및 줄 수를 계산해야합니다 그 다음 결과를 표시합니다.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; 
} 
+0

ifstream :: getLine'의 경우 기본 구분 기호는 '\ n'입니다. 나는 당신의 텍스트가 3 개의 단락을 포함하고 그것이 단지 3 '\ n'문자를 포함한다고 생각한다. 그래서 당신은 3을 줄 수만큼 얻는다. – sanastasiadis

+0

단어의 수는 공백 문자를 확인하는 것이 문제라고 생각합니다. 어쩌면 공간 'OR'기간 '을 확인하십시오.' 더 좋을 것입니다. – sanastasiadis

+0

"이 문자열"을 고려하십시오. 두 단어가 있지만 * 많은 * 공백이 있습니다. "이 문자열"도 고려하십시오. 두 단어와 단 하나의 공백이 있습니다. 마침내 "what-about-this"? 한 마디인가 세 마디인가? (오, 잊지 마세요 ""- 그것은 제로 단어입니다). –

답변

0

라인 수의 개념은보기 개념입니다. 파일에 인코딩되지 않았습니다. 당신이 줄 수 있었다 창의 문자 폭을 지정하고 싶다면

enter image description here

enter image description here

: 다음 하나의 단락은 한 줄 또는 16 개 라인 에디터 윈도우의 크기에 따라 표시 할 수 있습니다 그것으로부터 계산 될 수 있지만, 단락과 단어 수는 당신이 할 수있는만큼 좋습니다. 그리고 성공적으로 얻기 위해 매우 간단 ifstream infile을 열어 주어 :

auto numoflines = 0; 
auto numofwords = 0; 
string paragraph; 

while(getline(infile, paragraph)) { 
    numofwords += distance(istream_iterator<string>(istringstream(paragraph)), istream_iterator<string>()); 
    ++numoflines; 
} 

cout << "Number of words: " << numofwords << "\nNumber of lines: " << numoflines << endl; 

참고 :

비주얼 스튜디오 당신이 구성해야한다는 점 사용하지 않는 때문에 경우 istringstream의 인라인 건설을 지원 별도의 줄에.