我的目标是编写一个程序,从输入句子中读取多达100个字符,然后从存储的数据中输出3个字符。该输入句子的反转,数组的奇数元素和数组的偶数元素。因此我有3个printf函数。我有2个单独的代码来做这个,无法弄清楚如何将两者结合起来。
#include <stdio.h>
int main(void){
int i, j;
char str[100];
printf("Enter String\n");
fgets(str, sizeof str, stdin);
printf("\nString in Reverse Order\n");
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == '\n')
{
for(j = i - 1; j >= 0 && str[j] != ' '; j--)
printf("%c", str[j]);
printf(" ");
}
i++;
}
printf("\n");
return 0;
}
我的第二个代码是:
#include <stdio.h>
#include <string.h>
int main() {
char string[100], even[100], odd[100], i, j, k;
i = j = k = 0;
printf("Enter your input string:");
fgets(string, 100, stdin);
string[strlen(string) - 1] = '\0';
while (string[i] != '\0') {
if (i % 2 == 0) {
odd[j++] = string[i];
} else {
even[k++] = string[i];
}
i++;
}
odd[j] = even[k] = '\0';
printf("Characters at odd position: %s\n", odd);
printf("Characters at even position: %s\n", even);
return 0;
}
所以我一直在搞乱它并接受你的所有输入。我到目前为止的代码如下。我正在使用Odd和Even工作,但是当我输入'Hello'时,反向顺序中的字符串说:'eH lleH'..我一直在试图将其分解以查看问题出现在哪里但我认为我是遗失了什么。
#include <stdio.h>
#include <string.h>
int main() {
int m;
char string[100], even[100], odd[100], i, j, k;
i = j = k = 0;
//get the input string from the user
printf("Enter your input string:");
fgets(string, 100, stdin);
printf("\nString in Reverse Order\n");
string[strlen(string) - 1] = '\0';
while(string[i] != '\0'){
if(string[i] == ' ' || string[i] == '\n' || i % 2 == 0)
{
for(m = i - 1; m >= 0 && string[m] != ' '; m--)
printf("%c", string[m]);
printf(" ");
odd[j++] = string[i];
}
else {
even[k++] = string[i];
}
i++;
}
//terminating even and odd string with NULL
odd[j] = even[k] = '\0';
printf("\n");
//print the charactersa at odd position and even positions
printf("Characters at odd position: %s\n", odd);
printf("Characters at even position: %s\n", even);
return 0;
}