我正在尝试制作循环ASCII值介于32到126 之间的程序,然后将用户给出的字符串每个字符的值加10 并打印出来屏幕。示例: - 如果用户输入字符串'“xyz”,输出为'130 131 132'而不是此输出应该像'35 36 37'。这是我的代码
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter a string: ");
fgets(str,100,stdin);
str[strcspn(str,"\n")]='\0';
printf("String is: %s\n",str);
printf("\nASCII value in Decimal is: ");
while(str[i]!='\0')
{
printf("%d ",str[i]);
i++;
}
printf("\n\nAfter adding '10',ASCII value changes to: ");
for(i = 0; i < str[i]; i++)
{
printf("%d ",str[i] += 10);
}
getch();
}
我不知道数组和递归,因为它们不在我大学的课程中,所以我不知道是否可以用它们中的任何一个来完成。
答案 0 :(得分:1)
当您像在凯撒班次或ROT47中那样“旋转”字符时,您必须考虑在范围之外移动。你可以通过在溢出后减去范围的宽度来做到这一点:
s[i] = s[i] + shift;
if (s[i] >= 127) s[i] -= (127 - 33);
或对有效范围内从零开始的索引进行模运算。:
s[i] = 33 + (s[i] - 33 + shift) % (126 - 33);
请注意,这些方法仅在班次为正时才有效。您可以通过使移位范围宽度减去移位来解释负移位。您还应确保不要触摸有效范围之外的字符。
这是一个小程序,它实现了旋转ASCII范围和打印ASCII值的功能:
#include <stdlib.h>
#include <stdio.h>
#define LO 33 // inclusive lower bound of ASCII shift region
#define HI 127 // exclusive upper bound of ASCII shift region
void asciirot(char *s, int shift)
{
while (shift < 0) shift += (HI - LO);
for (int i = 0; s[i]; i++) {
if (LO <= s[i] && s[i] < HI) {
s[i] = LO + (s[i] - LO + shift) % (HI - LO);
}
}
}
void putascii(const char *s)
{
printf("{");
for (int i = 0; s[i]; i++) {
if (i) printf(", ");
printf("%d", s[i]);
}
puts("}");
}
int main()
{
char str[] = "The quick brown fox jumps over 1,206 lazy dogs!";
puts(str);
asciirot(str, 10);
puts(str);
putascii(str);
asciirot(str, -10);
puts(str);
putascii(str);
return 0;
}