接受rn输入C程序
我想问一下我怎么能接受rn而不把它改成rn, with fgets.
我希望程序将 转换rn为换行符,而不是将其打印为字符串。
当前代码:
char buff[1024];
printf("Msg for server: ");
memset(buff, 0, sizeof(buff));
fgets(buff, sizeof(buff), stdin);
printf(buff);
输入:
testrntest2
testrntest2
我想要的输出:
test
test2
我目前的输出:
回答
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);
}