2013-11-14 14 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

也许你应该考虑在擦除后删除中断。

相关问题