gpt4 book ai didi

c++ - 字符串末尾的未知字符

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:02 24 4
gpt4 key购买 nike

这是一个来自hackerrank的练习题:https://www.hackerrank.com/challenges/caesar-cipher-1 .我的输出与程序的预期输出匹配,但输出字符串末尾有一个未知字符。有人能告诉我未知字符是如何出现在字符串末尾的吗?这是我的代码:

#include <iostream>
#include <string>
#include<cstdio>
using std::cin;
using std::string;
using std::cout;
using std::endl;

int main()
{
int k,n;
string text;
cin>>n;
cin>>text;
cin>>k;

for (int i = 0; i <n; i++)
{
if(text[i] != '\0') //check if the character is null
{
if(isalpha(text[i])) //check if the character is alphabet
{
int d=(int)text[i] ; //obtain the ascii value
int t=d+k; //obtain the encrypted value
if(t>122) //if the encrypted value of character is greater than 122
{
int extra=t-122;
int letter=97 +(extra-1);
string ans= string()+char(letter);
cout<<ans;
}

string ans= string()+char(t); //print the encrypted character
cout<<ans;
}
else //if the character is not string, then print it just like that
{
cout<<text[i];
}
}
}
}

示例输出:qmhhpi-Syxd

我的输出:qmhhpi-Syxd~

最佳答案

您的代码中几乎没有错误:

  1. if(t>122) ,您正在检查加密字符(通过凯撒密码)的值是否大于 122(Z 的 ASCII)。但是,如果它的值最初在 A-Z 范围内,然后添加了 key 呢?
    因此,这两行是不正确的。
    int extra=t-122;
    int letter=97 +(extra-1);
  2. 您的代码不连贯。就像您已经将字符串的长度指定为 n 一样, 那你为什么要用 if(text[i] != '\0') .
    还有,为什么要用
    string ans= string()+char(t); cout<<ans; .
    正如@chris 所指出的,这两行可能只是 cout << char(t);
  3. 由于K 可以在[0,100] 之间变化,因此最好将其MOD 取为26。您可以在此处检查正确的代码:Ideone link

关于c++ - 字符串末尾的未知字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com