C 删除字符串末尾的换行符,行为很奇怪

标签 c string newline

所以我有以下代码:

printf("the output is: %s.\n", intCAPass);

打印以下内容:

the output is: intercapass
.

因此,我尝试了以下两个选项来删除字符串末尾的换行符 intCAPPass:

intCAPass[strlen(intCAPass)- 1] = '\0';
strtok(intCAPass,"\n");

但两者都给出了以下输出:

.he output is: intercapass

所以我想知道这里发生了什么。

更多信息:

操作系统:Linux

变量intCAPPass从读取包含interca\n的文件的函数接收字符串。因此,我使用一个缓冲区来复制整个文件,最后我执行 buffer[len] = '\0'; ,在某些时候我认为这可能会导致一些问题,但我不这样做不这么认为。

最佳答案

.he output is: intercapass

您有一个以输入字符串结尾的 Windows 样式 CRLF (\r\n) 行。 当最后一个换行符 \n 被删除时,回车符 \r 会留在字符串中。打印时,它将输出移回行首。因此,最后一个点会覆盖输出行的第一个字母。

这些应该表现出类似的行为:

printf("string one: %s.\n", "blah\r\n");
printf("string two: %s.\n", "blah\r");

对照 \r 检查字符串末尾 \n 之前的字符,并将该字符也删除。

关于C 删除字符串末尾的换行符,行为很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43902533/

相关文章:

c - printf 不在 eclipse c 的控制台中打印

string - 这个用大小解析字符串的概念有技术名称吗?

Javascript将字符串分成不同的变量

python - 如何按 x 行读取文本文件,但 x 未知?

c - munmap_chunk() : invalid pointer error

c - 在 C 中访问共享内存时出现段错误

android - 在 TextView 上添加新行 `\n' 将不起作用

android - 换行符的歧义行为

c - 分配内存给 int *a[13][13] 类型的变量

java - 我需要让扫描仪检查输入是否为 "quit",如果不是,则接受一个整数