C++ 我的程序只处理输入的一行
我在做凯撒密码。解决方案的一般步骤如下:C++ 我的程序只处理输入的一行,c++,C++,我在做凯撒密码。解决方案的一般步骤如下: 将消息读入大缓冲区或字符串对象 要么删除空格和标点符号,要么不删除(对于 如果你这样做了,你可以阅读 然后计算消息中的字符数 选择第一个大于消息长度的完美正方形, 分配一个大小相同的字符数组 将消息从左到右读入一个大小相同的正方形数组, 自上而下 将信息从上到下、从左到右写出来,你就已经 把它编成百科全书 我的代码: #include <iostream> #include <cstdlib> #include <str
- 将消息读入大缓冲区或字符串对象
- 要么删除空格和标点符号,要么不删除(对于 如果你这样做了,你可以阅读
- 然后计算消息中的字符数
- 选择第一个大于消息长度的完美正方形,
分配一个大小相同的字符数组 - 将消息从左到右读入一个大小相同的正方形数组, 自上而下
- 将信息从上到下、从左到右写出来,你就已经
把它编成百科全书
#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;
}
示例1工作,而示例2不工作,因为有多行。我感觉它与while(getLine)函数有关,但我不知道到底要更改什么。您在这里做什么:
while (getline(cin, buffer))
{
buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
break;
}
每次使用getline时都将新行保存到缓冲区。我的意思是,每次有getline()
时,您的缓冲区将被替换,而不是追加
试试这个:
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;
}
也许你应该考虑删除删除后的中断。
我没有意识到,问题是没有选择写多行。现在应该可以了。
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;
}