我想问一下如何接受\r\n
而不将其更改为\\r\\n
,带有fgets
。
我希望程序将 \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
答案 0 :(得分: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);
}
答案 1 :(得分:2)
[Edit] 我现在怀疑 OP 正在输入 \ r \ n 而不是 carriage返回 换行。
我将保留以下内容以供参考。
在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
}
答案 2 :(得分:2)
您需要用换行符替换 de \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"
分隔的子字符串,如果这是一个问题,则只会替换该特定子字符串,所有内容其他保持不变。
答案 3 :(得分:0)
在您的输入字符串中,“\r”有两个字符:'\' & 'r'。但 '\r' 是单个字符。 "\r\n" 是一个 4 字节的字符串,而 "\r\n" 是一个 2 字节的字符串。
如果非要这样做,在gets之前写一个字符串替换函数