c - 使用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;
}
解决方案
你非常接近..只需将提示在循环中进一步向下移动。另请注意,随后的“输入”消息与最初的消息不同,自动评分器可能正在检查这一点。
#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;
}
推荐阅读
- apache-kafka - Kafka 主题未创建为空
- apache - 如何在 PerPostConfigRequire 执行的代码中获取“我的”VHOST?
- node.js - 从 iOS 上传图片太慢
- python - 通过对组的聚合替换列的值
- laravel - 如何响应 message() 请求
- java - 如何仅延迟特定方法?
- angular - angular-bootstrap-datetimepicker 可以与 bootstrap3 一起使用吗?
- ruby-on-rails - Symbol 对象上的 Ruby 文档具有误导性
- nuget - 无法下载工件时的通知
- algorithm - 三胞胎数