2011-04-28 74 views
0

我有一個簡單的自動換行功能,它將一個長字符串作爲輸入,然後將該字符串分解爲更小的字符串,並將它們添加到稍後輸出的數組中。現在最後一個字或兩個字不是輸出。這是主要問題。不過,我也想改進功能。我知道這很凌亂。我想知道是否有更好的方法來解決這個問題。我認爲陣列是不必要的,但我不知道該怎麼做。數組填充所有較小的字符串後,我只是將它們輸出到一個文本文件。任何建議將不勝感激。修復/改進自動換行功能

這裏的自動換行功能:

void WordWrap(string inputString, string formatedAr[], const int SIZE) 
{ 
    unsigned int index; 
    unsigned int word; 
    unsigned int max = 65; 
    string outWord; 
    string outLine; 

    outWord = ""; 
    outLine = ""; 
    word = 0; 

    for(int i = 0; i < SIZE; i++) 
    { 
     formatedAr[i] = ""; 
    } 

    for(index = 0; index <= inputString.length(); index++) 
    { 
     if(inputString[index] != ' ') 
     { 
      outWord += inputString[index]; 
     } 
     else 
     { 
      if(outLine.length() + outWord.length() > max) 
      { 
       formatedAr[word] = outLine; 
       word++; 
       outLine.clear(); 
      } 
      outLine += outWord + " "; 
      outWord.clear(); 
     } 
    } 
    formatedAr[word] = outLine; 
} 

而這正是我所說的功能和輸出數組:

WordWrap(dvdPtr -> synopsis, formatedAr, SIZE); 

index = 0; 

while(index < SIZE && formatedAr[index] != "") 
{ 
    outFile << formatedAr[index] << endl; 
    index++; 
} 
+0

您是否嘗試過調試程序?你學到了什麼? – 2011-04-28 07:39:40

+0

您可以使用std :: vector而不是固定大小的數組fortribar。您也可以使用strtok(請參閱http://msdn.microsoft.com/en-us/library/2c8d19sb.aspx)標記輸入文本。 – 2011-04-28 07:59:19

回答

1

下面是一個示例代碼。

#include <iostream> 
#include <sstream> 
#include <string> 
#include <vector> 

using namespace std; 

void WordWrap(const string& inputString, vector<string>& outputString, unsigned int lineLength) 
{ 
    istringstream iss(inputString); 

    string line; 

    do 
    { 
     string word; 
     iss >> word; 

     if (line.length() + word.length() > lineLength) 
     { 
     outputString.push_back(line); 
     line.clear(); 
     } 
     line += word + " "; 

    }while (iss); 

    if (!line.empty()) 
    { 
     outputString.push_back(line); 
    } 
} 

/* 
A simple test: 

Input string: "aaa bbb ccccccc dddd d111111111111111 33333 4444444444 222222222 ajdkjklad 341343" 

Length per line: 20 

Output lines of strings: 

Line 1: aaa bbb ccccccc dddd 
Line 2: d111111111111111 
Line 3: 33333 4444444444 
Line 4: 222222222 ajdkjklad 
*/