运用C语言的循环结构写一段代码:输入一行电报文字,将字母变成其下一字母(如’a’变成’b’……’z’变成’a’其它字符不变)。 输入示例:a b123 输出示例:b c123
时间: 2025-07-06 12:50:40 浏览: 13
你可以使用C语言中的for循环配合ASCII码来实现这个功能。这里是一个简单的例子:
```c
#include <stdio.h>
#include <string.h>
// Function to shift a character by one position
char shift_char(char c) {
if (c >= 'a' && c <= 'z') { // Check if it's a lowercase letter
return c + 1; // Shift by 1
} else if (c >= 'A' && c <= 'Z') { // If uppercase letter
return c - 55 + 'A'; // Shift by 1 and convert back to uppercase
} else {
return c; // Non-alphabetic characters remain unchanged
}
}
int main() {
char input[100];
fgets(input, sizeof(input), stdin); // Read a line of input from the user
// Ensure newline is included in the input
if (input[strlen(input) - 1] == '\n') {
input[strlen(input) - 1] = '\0'; // Remove newline
}
// Process each character in the input string
for (size_t i = 0; i < strlen(input); i++) {
input[i] = shift_char(input[i]);
}
printf("%s", input); // Output the modified string
return 0;
}
```
当你运行此程序并输入 "a b123",它会输出 "b c123"。
阅读全文