2014-12-05 27 views
0

我一直在努力與這幾個小時,但我需要幫助格式化一些輸出。基本上,我有一個二維陣列arr,我想在3×70組以進行打印,即C++ - 列格式

aaaaaa ... a //Columns 1-70 
bbbbbb ... b //Columns 1-70 
cccccc ... c //Columns 1-70 
      //newline 
      //newline 
      //newline 
aaaaaa ... a //Columns 1-70 
bbbbbb ... b //Columns 1-70 
cccccc ... c //Columns 1-70 

//and so on like that until all of top, mid, and bot is printed out 

aaaa....a其中對應於arr[0]bbbbb....b對應於arr[1],和cccc...c對應於arr[2]

另一部分是arr對應於三個一維數組topmidbot。正如您可以猜到的,aaaa...aaatop,bbbb...bbb中的值是mid中的值,而ccc....cccbot中的值。 topmidbot的長度全部相同,因此一個字段length已被分配給該值。

我當前的代碼是(不包括進口):

string alignToString; 
stringstream out; 

char arr[3][70]; 


for (int column = 1; column <= length; ++column) 
{ 
    out << top[column - 1]; 
    if (column % 70 == 0) 
    { 
     out << endl; 
     for (int column = 1; column < 70; ++column) 
     { 

     } 
    } 

    arr[0][column] = top[column - 1]; 
    arr[1][column] = mid[column - 1]; 
    arr[2][column] = bot[column - 1]; 

    if (column % 70 == 0) 
    { 
     break; 
    } 

//TODO: output out.str(); 
} 

此代碼不能正常工作,效果顯着。我有想法,也許我可以輸出每列三個一組,並且一旦列%70 = 0,我會添加換行符,但我似乎無法弄清楚。如果有人能幫助我解決這個問題,或者爲這個問題提供更好的解決方案,我將不勝感激。先謝謝你。

+0

我不知道top,mid,bot的作用是什麼。其實我不明白你想做什麼。你也沒有寫出當前的輸出是什麼,它與你想要的不同。如果你真的想得到答案,你應該改寫你的問題。 – Silicomancer 2014-12-05 08:03:04

回答

0

這個問題有點不清楚 - 什麼是arr用於?您是否真的想要將topmidbot中的每一行復制到arr以供以後使用以及打印?或者它只是您嘗試解決方案的一部分?如果您不需要將其用於其他目的,那麼使用您的數據將三個數組中的數據複製到這些臨時緩衝區中沒有任何好處。

另一個不明顯的位是您是要內存字符串表示還是實際直接打印到cout。如果是後者,那麼事先暫時寫入緩衝區並沒有真正的好處 - 字符將以相同的順序寫入。

我假設你打算這兩個,但如果不是解決方案可以運行得更快。談到速度,雖然編譯器在優化它的過程中越來越好,但每個角色的工作可能會非常緩慢。使用std::ostream::write()可以一次處理長時間的字符更清晰,更快速。

const size_t maxColumn = 70; 

char arr[3][maxColumn]; 

using CharIteratorPair = std::pair<char *, char *>; 

CharIteratorPair myArrays[] = { 
    { top, arr[0] }, 
    { mid, arr[1] }, 
    { bot, arr[2] }}; 

std::stringstream out; 

for (size_t i = 0 ; i < length; i += maxColumn) { 
    size_t gulpSize = std::min(maxColumn, length - i); 

    for (auto& source: myArrays) { 
     out.write(source.first, gulpSize); 
     out << std::endl; 

     // Remove this line if you don't need to copy the data 
     // into "arr" 
     std::copy_n(source.first, gulpSize, source.second); 

     std::advance(source.first, gulpSize); 
    } 

    // "arr" has now been filled in, do other processing here for each 
    // group of three rows as needed 
} 

// out has now been filled in, ready for extracting with .str() 
// or printing to std::cout etc. 

std::cout << out.str();