循环ASCII值之间32到126和添加值,将其

问题描述:

我试图让程序环32之间的ASCII值126,然后由用户和打印给出添加字符串的每个字符的值它在屏幕上。例如: - 如果用户输入字符串“‘XYZ’,则输出是‘130 131 132’,而不是这个输出应该像'35 36 37”。这里低于循环ASCII值之间32到126和添加值,将其

#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

你想在32范围内旋转字符到ROT47中的126?然后你必须把字符带到一个基于零的范围,并使用模算法:'c = 32 +(c-32 + shift)%(127 - 32)'。 (尽管ROT47保持空间不变,并开始从ASCII 33开始移位。) –

+1

你的循环结束控制在for(for i = 0; i

当您在凯撒班或“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; 
} 
+0

谢谢你很多先生... –