c - 为什么无论测试用例的数量如何,都会重复打印第一个字符串以及如何更正它。请更正。使用c语言

标签 c

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

int main(void) {

    int i, j, t;
    scanf("%d", &t); // enter the number of test cases 
    getchar();
    char input[11111];
    for(i=0; i<t; i++){
        scanf("%[^STOP]", input); // take input till STOP will come
        printf("%s\n", input); 
// this code print first input as many time as number of test cases in the code that will we provide through variable t;
    }
    return 0;
}

最佳答案

将代码更改为

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

int main(void) {

    int i, j, t;
    char ch;
    scanf("%d", &t); // enter the number of test cases 
    getchar();
    char input[11111];
    for(i=0; i<t; i++){
        scanf("%[^STOP]", input); // take input till STOP will come
        while((ch=getchar())!='\n'&& ch!= EOF);
        printf("%s\n", input); 
// this code print first input as many time as number of test cases in the code that will we provide through variable t;
    }
    return 0;
}

该问题是由于缓冲引起的。 scanf()\n 发送到输入缓冲区,下一个 scanf() 读取它。这就是造成问题的原因。

如果您想了解更多信息,只需在 Stack Overflow 或 Google 中搜索 input buffer 即可。这个问题已经被讨论过很多次了。

关于c - 为什么无论测试用例的数量如何,都会重复打印第一个字符串以及如何更正它。请更正。使用c语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670393/

相关文章:

c - 为什么相同的浮点常量在 Fortran 和 C 中打印不同?

c - 使用栈将中缀表达式转换为前缀时,如果被扫描的和栈顶运算符的优先级相同,应该怎么办?

c - 避免在 C 错误处理中重复

c - CMBC 未报告看似无效的内存访问

c - 使用哈希的 Shell 安全性

c# - TestDriven.NET 和 native C 库

c - 下面的类型转换在 C 中做了什么?

c - 在 C 中使用 strdup 的奇怪错误

c - 客户端中的 OpenSSL Bio_gets

c - 在 OpenGL C Linux 中移动特定对象