接受输入的C程序

4

我想问如何在使用 fgets 时接受 \r\n 而不将其转换为 \\r\\n,使程序将其作为换行符进行转义。

我希望程序将 \r\n 转换为换行符而不是将其打印为字符串。

当前代码:

char buff[1024];
printf("Msg for server: ");
memset(buff, 0, sizeof(buff));
fgets(buff, sizeof(buff), stdin);
printf(buff);

输入:

test\r\ntest2

我想要的输出:

test
test2

我的当前输出:

test\r\ntest2

1
你需要将这四个字符"\r\n"替换为新行字符。 - Vlad from Moscow
1
fgets 不会转换输入,它会用获取到的确切数据填充缓冲区。如果您想修改输出,您需要自己进行修改。 - Konrad Rudolph
“accept \r\n without changing it to \r\n” 不是很清楚。到底改变了什么? - wildplasser
1
Jerry,当你写下“Input: test\r\ntest2”时,它是由14个按键组成的吗?t, e, s, t, \, r, \, n, t, e, s, t, 2, enter?如果不是,那是什么? - chux - Reinstate Monica
1
@chux-ReinstateMonica 是的,我输入了那14个键。抱歉,我误读了你的问题。 - Jerry
显示剩余8条评论
4个回答

5

OP正在输入

\ r \ n,并希望将其更改为换行符。

处理输入字符串,查找转义序列的开始字符\

if (fgets(buff, sizeof buff, stdin)) {
  char *s  = buff;
  while (*s) {
    char ch = *s++; 
    if (ch == '\\') {
      switch (*s++) {
        case 'r': ch = '\r'; break; // or skip printing this character with `continue;`
        case 'n': ch = '\n'; break; 
        case '\\': ch = '\\'; break;  // To print a single \
        default: TBD();  // More code to handle other escape sequences.
      }
    }
    putchar(ch);
  } 

非常感谢你。我已经将我的一部分代码与你的解决方案结合起来,现在它可以正常工作了。 :) - Jerry
@Jerry 请查看示例 - chux - Reinstate Monica

2
您需要用换行符替换\r\n子字符串:

演示实例

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

int main(void)
{
    char buff[1024];

    printf("Msg for server: ");
    fgets(buff, sizeof(buff), stdin);

    char *substr = strstr(buff, "\\r\\n"); //finds the substring \r\n

    *substr = '\n'; //places a newline at its beginning

    while(*(++substr + 3) != '\0'){ //copies the rest of the string back 3 spaces 
        *substr = substr[3];   
    } 
    substr[-1] = '\0'; // terminates the string, let's also remove de \n at the end

    puts(buff);
}

输出:

test
test2

如果您的主字符串中包含其他\字符、"\n""\r"分隔的子字符串,那么这个解决方案将允许您替换特定的子字符串而保留其他内容不变。


2
[编辑] 我现在怀疑OP输入的是 \ r \ n 而不是 回车 换行

为了参考,我将下面的内容保留。


fgets()之后使用strcspn()

if (fgets(buff, sizeof buff, stdin)) {
  buff[strcspn(buff, "\n\r")] = '\0';  // truncate string at the first of \n or \r
  puts(buff);  // Print with an appended \n
}  

4个字符,我的意思是 - anastaciu
所以OP输入了字符串“..\n\r...”,想要将其更改为换行符,是这样吗? - anastaciu
让我们在聊天中继续这个讨论 - chux - Reinstate Monica

0
在您的输入字符串中,"\r" 有两个字符:'\' 和 'r'。但是 '\r' 是一个单独的字符。 "\r\n" 是一个4字节的字符串,而 "\r\n" 是一个2字节的字符串。
如果您必须这样做,请编写一个字符串替换函数来代替获取函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接