Design and implement a program in C, that receives as input from standard input: • a word w in the first line (no spaces, no more than 80 characters, word finishes with the new line, excluding this character), • an integer value n, between 0 and 127, in the second line, • an encoded text (all the text from the third line until the end of the input). The program then checks if when decoding the encoded text using n (each character is decremented, modulo 128, by n in its ASCII encoding), the word w is found. If so, the word ”YES” is printed out on standard output, highlighted in green. If not, then the word ”NO” is outputted on standard output, highlighted in red. You can assume that the encoded text is ASCII, and the input is formatted as indicated above.
时间: 2024-01-21 18:01:50 浏览: 25
Sure, I can help you with that. Here's a possible implementation of the program you described:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#define MAX_WORD_SIZE 80
#define ASCII_SIZE 128
void print_colored(char* text, char* color) {
printf("\033[%sm%s\033[0m", color, text);
}
bool decode_and_check(char* word, int n, char* encoded_text) {
int len = strlen(encoded_text);
char decoded_text[len + 1];
for (int i = 0; i < len; i++) {
decoded_text[i] = ((encoded_text[i] - n) % ASCII_SIZE + ASCII_SIZE) % ASCII_SIZE;
}
decoded_text[len] = '\0';
if (strstr(decoded_text, word) != NULL) {
return true;
} else {
return false;
}
}
int main() {
char word[MAX_WORD_SIZE + 1];
int n;
char encoded_text[ASCII_SIZE];
fgets(word, MAX_WORD_SIZE + 1, stdin);
scanf("%d", &n);
getchar(); // read the newline character after n
fgets(encoded_text, ASCII_SIZE, stdin);
encoded_text[strcspn(encoded_text, "\n")] = '\0'; // remove the newline character from encoded_text
if (decode_and_check(word, n, encoded_text)) {
print_colored("YES\n", "32"); // green color
} else {
print_colored("NO\n", "31"); // red color
}
return 0;
}
```
The program reads the input from standard input using `fgets()` and `scanf()`, and then applies the decoding algorithm to the `encoded_text` string using a loop and the `%` operator. The resulting `decoded_text` string is then checked for the presence of the `word` substring using `strstr()`. Finally, the program prints either "YES" or "NO" in the corresponding color using the `print_colored()` function and ANSI escape codes.
I hope this helps! Let me know if you have any questions.