C ++ Цезарь программа выполняет неверный символ

Вот что я получаю, когда пытаюсь зашифровать «Это тестовое предложение!»: «Ymnxp p t »

Я уже проверял свою часть шифрования, и она работала нормально.

Может кто-нибудь сказать мне, что я здесь не так сделал?

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include "unistd.h"
using namespace std;void displayUsage(){
// Displays how to use this program
// TODO
cout << "Instruction: \n use -r to give rotation number \n use -f to give file name" <<endl;
}int main(int argc, char **argv){

string text;
char* input_file_name;
int rotation;
bool have_rotation = false;
bool have_input_file_name = false;// process command-line arguement
int opt = 0;
extern char *optarg;
static const char* opt_string = "r:f:";
opt = getopt( argc, argv, opt_string);
while(opt != -1) // While there are parameters to parse, do so
{
switch(opt)
{
case 'r':
have_rotation = true;
rotation = atoi(optarg);
break;
case 'f':
have_input_file_name = true;
input_file_name = optarg;
break;
default:
displayUsage();
return 1;
}
opt = getopt( argc, argv, opt_string);  // Pull the next parameter, or 0 if none.
}

if(!have_rotation)
{
displayUsage();
return 0;
}

if(have_rotation)
{
if(have_input_file_name)
{
ifstream file(input_file_name);
string text2, temp;
while(!file.eof())
{
getline(file, temp);
text2 += temp;
text2 += "\n";
}
text = text2[text2.size()-2];
}
else
{
cout <<"Enter text:"<<endl;
cin >> text;
}
}

char cipher[text.size()];

for(int i=0; i<text.size(); i++)
{
cipher[i] = text[i];
if(islower(cipher[i]))
{
cipher[i] = (cipher[i] - 'a' + rotation)%26 + 'a';
}
else if(isupper(cipher[i]))
{
cipher[i] = (cipher[i] - 'A' + rotation)%26 + 'A';
}
}

cout <<cipher<<endl;

return 0;
}

0

Решение

Я думаю, ошибка в том, что вы не прервали свою cipher массив с ‘\ 0’.

Функция печати будет обрабатывать символы из массива (и, возможно, за его пределами), пока не найдет символ ‘\ 0’.

Ваш массив должен быть на один больше больше, чтобы учесть этот завершающий символ.

Или избавиться от char массив и использование std::string,

3

Другие решения

Я могу запустить мой код, если наберу предложение вручную. Он ничего не распечатывает, если я ввожу текстовый файл.

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include "unistd.h"
using namespace std;void displayUsage(){
// Displays how to use this program
// TODO
cout << "Instruction: \n use -r to give rotation number \n use -f to give    file name" <<endl;
}

char caesar(char c, int r)
{
if(isalpha(c))
{
if(islower(c))
{
c = (((c-97)+r)%26)+97; // 97 is a value of 'a'
}
else if(isupper(c))
{
c = (((c-65)+r)%26)+65; // 65 is a value of 'A'
}
}
return c;
}int main(int argc, char **argv){

string text;
char* input_file_name;
int rotation;
bool have_rotation = false;
bool have_input_file_name = false;// process command-line arguement
int opt = 0;
extern char *optarg;
static const char* opt_string = "r:f:";
opt = getopt( argc, argv, opt_string);
while(opt != -1) // While there are parameters to parse, do so
{
switch(opt)
{
case 'r':
have_rotation = true;
rotation = atoi(optarg);
break;
case 'f':
have_input_file_name = true;
input_file_name = optarg;
break;
default:
displayUsage();
return 1;
}
opt = getopt( argc, argv, opt_string);  // Pull the next parameter, or 0 if none.
}

if(!have_rotation)
{
displayUsage();
return 0;
}

if(have_rotation)
{
if(have_input_file_name)
{
ifstream file(input_file_name);
string text2, temp;
while(!file.eof())
{
getline(file, temp);
text2 += temp + "\n";
}
text = text2[text2.size()-2];
}
else
{
cout <<"Enter text:"<<endl;
getline(cin, text);
}
}

string output = "";
for(int i = 0; i < text.size(); i++)
{
output += caesar(text[i],rotation);
}
cout<<output<<endl;return 0;
}
0