c - 从用户获取字符串,然后将其从屏幕上删除

标签 c arrays string input scanf

这个简单的程序从用户获取字符(直到换行符)并打印它们:

#include <stdio.h>

int main()
{
    char local_message[200];
    scanf("%[^\n]%*c", local_message);
    printf("Your message is %s\n", local_message);

    return 0;
}

但是当我运行它时,我输入的字符仍然打印在屏幕上:

Hello World!
Your message is Hello World!

我输入的字符是“Hello World!\n”。我希望当我按“Enter”创建换行符 \n 字符时,我的消息会从屏幕上消失(同时存储到 char 数组中),这样我可以使用以下 printf 打印(并格式化)它。

操作系统是Linux。

这可能吗?怎么办?

最佳答案

您可以使用终端转义码来执行此操作。

#include <stdio.h>

int main ( ) {
    char local_message[200];

    scanf("%199[^\n]%*c", local_message);
    printf ( "\033[0A");//move cursor up one line
    printf ( "\033[2K");//clear line
    printf("\nYour message is %s\n", local_message);

    return 0;
}

编辑:
这将提供更多的控制并删除多于一行的输入。

#include <stdio.h>

int main ( ) {
    char local_message[200];

    printf ( "\033[2J");//clear screen and move cursor to upper left corner
    printf ( "\033[8;H");//move cursor to line 8
    printf("Enter Your message\n");
    scanf("%199[^\n]%*c", local_message);
    printf ( "\033[9;H");//move cursor to line 9
    printf ( "\033[J");//clear screen from line to end
    printf ( "\033[12;H");//move cursor to line 12
    printf("\nYour message is %s\n", local_message);

    return 0;
}

关于c - 从用户获取字符串,然后将其从屏幕上删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32035858/

相关文章:

c - 无需系统调用或 C 中的库函数即可从内存中逐字节读取

c++ - 包含 LPCTSTR 的函数

arrays - 带开关元件的最长子阵列

php - 我的 $_SESSION 变量只获取数组中每个索引的第一个字母

javascript - 如何通过复选框选择修改数组(只需修改一些内容就可以了)

c - 我的 C 程序生成不需要的输出

python 迭代动态分配的 Cython 数组

c - 有没有更好的方法来计算一维数组包含多少个元素?

ruby - 转义的 Ruby 正则表达式在用作文字正则表达式时不匹配。为什么?

javascript - 将字符串从一个 Node.js 实例传输到另一个 Node.js 实例