尝试验证它是否存在后,换行符删除不起作用 [英] Newline removal not working after trying to verify it exists
问题描述
我正在编写代码来解析一些输入数据并以特殊格式将其写入文件.我正在从每个字符串标记中删除一个换行符:
I am making a code to parse some input data and write it to a file in a special formatting. I am removing a newline from each string token as so:
token[strlen(token)-2] ='\0'
它是 -2
因为最后一个元素是 \0
.这非常有效.但是,输入数据的最后一个元素没有换行符,因此仅使用它最终会从最后一个输入集中删除倒数第二个字符.
It is -2
because the last element is \0
. This much works. However, the final element of the input data does NOT have a newline, so using just that ends up removing the second-to-last character from the last input set.
original input: 0.38
after running it through the removal: 0.3
显而易见的解决方案是在删除之前检查换行符是否存在.我这样做:
The obvious solution is to check if the newline is there before removing. I do this:
if(token[strlen(token)-2] =='\n') token[strlen(token)-2] ='\0';
但是,添加了 if 子句后,换行符就不再去掉了!我究竟做错了什么?来自整个代码的片段:
However, after adding the if clause, the newline is no longer removed! What am i doing wrong? Snippit from the whole code:
while((token = strsep(&line, ",")) != NULL){
if(x++ == 1){
fwrite(" <item>\n", 11, 1, fw);
fwrite(" <name>", 14, 1, fw);
fwrite(token, strlen(token), 1, fw);
fwrite("</name>\n", 8, 1, fw);
}
else if(isdigit(token[0])) {
if(token[strlen(token)-2] =='\n') token[strlen(token)-2] ='\0';
fwrite(" <SPC>", 13, 1, fw);
fwrite(token, strlen(token), 1, fw);
fwrite("</SPC>\n", 7, 1, fw);
fwrite(" </item>\n", 12, 1, fw);
}
}
推荐答案
你的换行符应该在 line[strlen(line)-1]
,但你可以在 Windows 下工作,其中换行符实际上包含回车符后跟换行符.这将解释为什么 line[strlen(line)-2]='\0'
成功删除行尾,但测试失败.
Your newline should be at line[strlen(line)-1]
, but you may work under Windows where a newline actually consists of a carriage return followed by a newline. This would explain why line[strlen(line)-2]='\0'
is successful in removing the end-of-line, but the test fails.
这篇关于尝试验证它是否存在后,换行符删除不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!