2013-11-14 21 views
2

我正在做一個凱撒塊密碼。解決方案的一般步驟如下:我的程序只處理輸入中的一行

  • 將您的消息讀取到大緩衝區或字符串對象中。

  • 要麼刪除空格和標點符號(如果你這樣做,敵人難以閱讀)。

  • 然後計算消息中的字符數。

  • 選取比消息長度大的第一個完美正方形,
    分配一個char大小的數組。

  • 將消息從左至右讀取爲該尺寸的正方形數組,從頂部到底部爲 。

  • 從上到下,從左到右書寫信息,你已經
    encyphered它。

我的代碼:

#include <iostream> 
#include <cstdlib> 
#include <string> 
#include <cstring> 
#include <ctype.h> 
#include <cmath> 
#include <functional> 
#include <numeric> 
#include <algorithm> 
#include <locale> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 

    int length = 0; 

    cout << "Enter a string: "; 

    string buffer; 
    char buff[1024]; 

    while (getline(cin, buffer)) 
    { 
     buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end()); 
     break; 
    } 

    length = buffer.length(); 
    int squareNum = ceil(sqrt(length)); 

    strcpy(buff, buffer.c_str()); 

    char** block = new char*[squareNum]; 
    for(int i = 0; i < squareNum; ++i) 
    block[i] = new char[squareNum]; 

    int count = 0 ; 

    for (int i = 0 ; i < squareNum ; i++) 
    { 
     for (int j = 0 ; j < squareNum ; j++) 
     { 
      block[i][j] = buff[count++]; 
     } 
    } 

    for (int i = 0 ; i < squareNum ; i++) 
    { 
     for (int j = 0 ; j < squareNum ; j++) 
     { 
      cout.put(block[j][i]) ; 
     } 
    } 

    return 0; 

} 

在大多數情況下,它的工作原理。我得到的問題是有多行輸入。

Ex. 1 
this is sample text suitable for a simulation of a diplomatic mission or a spy's instructions 

Ex. 2 
this is sample text suitable 
for a simulation of a diplomatic 
mission or a spy's instructions 

示例1的作品和示例2並不因爲有多行。我有一種感覺,它與while(getLine)函數有關,但我不知道要改變什麼。

回答

0

你在這裏做什麼:

while (getline(cin, buffer)) 
{ 
    buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end()); 
    break; 
} 

是節約新行緩衝每次使用函數getline時間。我的意思是,每次有getline()誘發您的buffer正在被替換,而不是附加。

試試這個:

string buffer = ""; 
string buff2; 

// You need to provide some way to let the user stop the input 
// e.g. ask him to declare number of lines, or what I recommend 
// check for an empty line given, which is implemented below: 

while (getline(cin, buff2)) 
    { 
     // now pressing [enter] after the last input line stops the loop 
     if (buff2.empty()) 
      break; 

     buff2.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end()); 
     buffer += buff2; 
    } 
+0

我沒有意識到第一個問題,那就是沒有選擇寫多行的選項。現在它應該工作。 –

+0

我用了類似的東西,它工作。謝謝! –

0

這個「破發」的「而」循環中 - 它打破了第一個「函數getline」通話後循環。這就是爲什麼你只有一條線。

0

也許你應該考慮在擦除後刪除中斷。

相關問題