我想问一下,如果不把rn
换成\r\n
,我怎么能接受CC_1呢?
我希望程序将rn
转换为换行符,而不是将其打印为字符串。
当前代码:
char buff[1024];
printf("Msg for server: ");
memset(buff, 0, sizeof(buff));
fgets(buff, sizeof(buff), stdin);
printf(buff);
输入:
testrntest2
我想要的输出:
test
test2
当前输出:
testrntest2
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);
}
[Edit]我现在怀疑OP正在输入rn而不是回车换行。
我将把下面的内容留作参考。
在fgets()
之后,使用strcspn())
if (fgets(buff, sizeof buff, stdin)) {
buff[strcspn(buff, "nr")] = ' '; // truncate string at the first of n or r
puts(buff); // Print with an appended n
}
您需要用换行符替换rn
子字符串:
现场演示
#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 rn
*substr = 'n'; //places a newline at its beginning
while(*(++substr + 3) != ' '){ //copies the rest of the string back 3 spaces
*substr = substr[3];
}
substr[-1] = ' '; // terminates the string, let's also remove de n at the end
puts(buff);
}
输出:
test
test2
这个解决方案将允许您在主字符串上有其他字符或
"n"
和"r"
分开的子字符串,如果这是一个问题,只有特定的子字符串将被替换,其他一切保持不变。
在你的输入字符串中,"有两个字符:'' &"r"。但是'r'是一个字符。" r n"是一个4字节的字符串,而"rn"是一个2字节的字符串。
如果你必须这样做,在get
之前写一个字符串替换函数