首页 > 解决方案 > 使用while和for循环在C中输出不匹配

问题描述

我正在尝试使用 userInput 的附加对话以及连续的 userInput 打印出我的反向字符串,直到 3 个因素为真。虽然我的程序正常工作,但我似乎无法确定打印顺序以匹配自动评分器的要求。

目前,程序获取 userInput 并将其打印出来,但仅在要求连续输入之后。我需要弄清楚如何在每个语句的正下方打印它,然后在之后的附加输入。 在此处输入图像描述

#include <stdio.h>
#include <string.h>

int main () {
   
   char userInput[50];
   int length;
   
   printf("Please enter a line of text (maximum 50 characters). Type done, Done, or d to exit program.\n");
   
   fgets(userInput, 50, stdin);
   userInput[strlen(userInput) - 1] = '\0';
   
   //compare userInput, while there userIput doesnt equal done, Done, or d loop for input
   while (strcmp(userInput, "done") != 0 && strcmp(userInput, "Done") != 0 && strcmp(userInput, "d") != 0) {
      printf("Please enter a line of text (maximum 50 characters). Type done, Done, or d to exit program.\n");
      length = strlen(userInput);
    //print userInput  
   for (int i = length - 1; i >= 0; --i) {
      printf("%c", userInput[i]);
   }
   printf("\n");
   fgets(userInput, 50, stdin);
   userInput[strlen(userInput) - 1] = '\0';
   }
   return 0;
}

标签: ccompare

解决方案


你非常接近..只需将提示在循环中进一步向下移动。另请注意,随后的“输入”消息与最初的消息不同,自动评分器可能正在检查这一点。

#include <stdio.h>
#include <string.h>

int main () {
   char userInput[50];
   int length;
   
   printf("Please enter a line of text (maximum 50 characters). Type done, Done, or d to exit program.\n");
   
   fgets(userInput, 50, stdin);
   userInput[strlen(userInput) - 1] = '\0';
   
   //compare userInput, while there userIput doesnt equal done, Done, or d loop for input
   while (strcmp(userInput, "done") != 0 && strcmp(userInput, "Done") != 0 && strcmp(userInput, "d") != 0) {
        // don't prompt for the next string here, print the reverse first
        // printf("Please enter another line of text (maximum 50 characters). Type done, Done, or d to exit program.\n");
        length = strlen(userInput);
        //print userInput  
        for (int i = length - 1; i >= 0; --i) {
            printf("%c", userInput[i]);
        }
        printf("\n");
        // move the next prompt to after the string reversal output
        printf("Please enter another line of text (maximum 50 characters). Type done, Done, or d to exit program.\n");
        fgets(userInput, 50, stdin);
        userInput[strlen(userInput) - 1] = '\0';
    }
    return 0;
}

示范


推荐阅读