c - 在 C 中,如何停止 gets() 从先前的输入中打印换行符?

标签 c newline stdio gets

我在 C 中使用 gets 时遇到问题。

...
int main()
{
    char test[20], m[20];
    int n;

    scanf("%d", &n);

    while(n)
    {   
        gets(test);
        test.kolona = n;

        m = decode(test); //some function

        printf("%s",m.sif);
        putchar('\n');

        scanf("%d", &n);
    }
}

当我输入数字并按 Enter 键时,它会在您输入字符串之前自动“打印”换行符。我搜索了一下,发现如果你在前面加上 gets 就可以避免这种情况,如下所示:

...
scanf("%d", &n);
gets(test)

while(n);
{
    gets(test);
    ...
}

但是随着循环的继续,它再次变得困惑:(

有没有一个优雅的解决方案?

最佳答案

要修复的示例

int main()
{
    char test[20], m[20];
    int n;

    scanf("%d%*c", &n);//skip the newline following the numeric input

    while(n)
    {   
        scanf("%19[\^n]", test);//gets has been abolished.
        //test.kolona = n;//The array does not have a member field.

        //strcpy(m, decode(test));//m = decode(test); //Can not be assigned to the array in this way 

        printf("%s\n", m);
        //putchar('\n');

        scanf("%d%*c", &n);
    }
}

关于c - 在 C 中,如何停止 gets() 从先前的输入中打印换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052862/

相关文章:

c - 使用 swapcontext() 或 getcontext() & setcontext() 为线程库编写 yield() 函数

c - 1.14 任务在 Kernighan,Ritchie "Programming with C"书中

javascript - 警报 javascript 中的换行符

c - 如何设置 fread 的起点?

C++ stdio::rename();同步?

CMSIS-驱动外设

c - 指向 char 的指针 - 增量运算符

shell - 如何修复大量文件的 “No newline at end of file” 警告?

java - 如何在java中打印int新行?

c++ - 我在标准库中遇到编译错误。这是怎么回事?