2017-12-05 9 views
0

사용자로부터 입력 텍스트를 읽고 각 단어를 인쇄하고 정렬 된 순서로 반복 한 횟수를 인쇄하는 프로그램을 만들려고합니다. (입력은 공백으로 구분되며 구두점을 사용할 수 있지만 새 줄은 사용할 수 없음)반복 횟수에 따라 입력 텍스트에서 단어를 정렬 하시겠습니까?

입력 예 : 저는 좋은 프로그래머이며 C 언어을 좋아합니다.

출력해야한다 :

  • A : 2 회
    I : 1 시간
    오전 : 1 시간
    좋은 : 1 시간

    ... 등등.

** 입력에 벡터와 클래스를 사용했지만 왜 여러 항목을 넣을 수 있는지 알 수 없습니다.


int main(){ /*creating vecotr called items of list class type*/ 
vector<word>items; 

/*creating a variable of list class type which is used to push data into the vector*/ 

word *element; 

/*Reading the input text seperated by white spaces*/ 
int size = 0; 
string text; 

cout << "Enter the text: " << endl; 
getline(cin, text); 

size = text.length(); 
int left_space = -1; 
int right_space = 0; 
string Sub_String; 

/*main loop for constructing substring of words and then manipulating them*/ 

for (int i = 0; i<size; i++) 
{ 

    /*splitting the string into words*/ 
    if (isspace(text[i]) || ispunct(text[i])) 
    { 
     right_space = i; 

     Sub_String = text.substr(left_space + 1, right_space - left_space - 1); 
     /*for first word just push it*/ 

     if (left_space == -1) 
     { 
      element = new word(); 
      element->set_data(Sub_String); 
      items.push_back(*element); 

     } 

     else 
     { 
      /*compare to vector's data */ 
      for (int j = 0; j < items.size(); j++) 
      { 
       if (Sub_String == items[j].data) 
       { 
        items[j].count = items[j].count + 1; 
       } 
       else 
       { 
        element = new word(); 
        element->set_data(Sub_String); 
        items.push_back(*element); 
       } 

      } 
     } 
      left_space = right_space; 
    } 

class word {public: 
word(); 
void set_data(string data_value); 
void printing_data(); 
void counter_addition(); 
int count; 
string data;}; 
단어는 출력이 정확한지 동일한 경우.

입력 : 생명 생명 생명 생명


출력 : 인생은 반복 : 4

내가 프로그래밍에 새로운 오전이를 통해 저를 도와주세요.

+0

기본적으로 각 단어 (반복문 2 개)를 반복하고 (strcmp) 및 증분 카운터를 사용하여 단어를 비교하십시오. 매번 새로운 변수를 만드는 대신 ar을 저장하고 구조체를 반복하면 작업을 더 쉽게 할 수 있기 때문에 구조체도 포함하십시오. 또한 프로그래밍에 익숙하지 않아 효율성을 목표로하지 않으므로 올바른 코드를 목표로 삼습니다. 하위 문자열을 사용하는 것보다 처리하기가 쉽기 때문에 사용자 입력을 파일에 저장하십시오. –

답변

2

문자열 값을 저장하고 std :: map < std :: string, int>에 저장하고 각 단어에 대해 이미지도에 있는지 확인하십시오. 있을 경우 카운트를 증가시킵니다. 반대의 경우 count = 1로 삽입하십시오.