【问题标题】:C Deleting the newline at the end of a string acting weirdC 在字符串末尾删除换行符,表现很奇怪
【发布时间】:2017-05-10 20:52:19
【问题描述】:

所以我有以下代码:

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

打印以下内容:

the output is: intercapass
.

所以我尝试了以下两个选项来摆脱字符串 intCAPass 末尾的换行符:

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

但两者都给我以下输出:

.he output is: intercapass

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

更多信息:

操作系统:Linux

变量intCAPass 接收来自函数的字符串,该函数读取包含@​​987654328@ 的文件。所以,我使用了一个缓冲区来复制整个文件,最后我做了buffer[len] = '\0';,在某些时候我认为它可能会导致一些问题,但我不这么认为。

【问题讨论】:

  • 请提供minimal reproducible example。不要只用文字描述代码,要展示出来。
  • 请显示更多代码... intCAPass 是如何定义和初始化的?
  • \r\n 的味道。您所在地区有窗户吗?
  • 文件来自Windows?
  • 保护它!

标签: c string newline


【解决方案1】:
.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");

检查字符串末尾\n 之前的字符与\r 是否一致,并将其也删除。

【讨论】:

  • 是的,已修复。谢谢你。我实际上考虑过,但我认为这些文件是在 linux 下创建的。这也是我提到操作系统的原因。
猜你喜欢
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
相关资源
最近更新 更多