C 中忽略换行符
我正在尝试编写一些读取文件并忽略换行符(\n)的代码,到目前为止我已经:
c = fgetc(fp);
for(int loop = 0; c != EOF; loop++)
{
if((c != '\n') && (c != '\\'))
{
buffer[loop] = c;
}
c = fgetc(fp);
}
但它似乎没有忽略“\n”位(不确定“\”)
并且对代码的布局感到抱歉,该网站似乎不喜欢我的 Opera 版本:(
编辑: 谢谢大家,我已经连续编码了大约 6 个小时,完全忽略了增量,这就是为什么我认为 \n 保持不变。
我也不知道 \r, uning Linux,但试图跨平台,所以这很有帮助。
I'm trying to write some code that reads a file and ignores the line breaks (\n), so far I have:
c = fgetc(fp);
for(int loop = 0; c != EOF; loop++)
{
if((c != '\n') && (c != '\\'))
{
buffer[loop] = c;
}
c = fgetc(fp);
}
but its just not seeming to ignore the '\n' bits (not sure about the '\')
And sorry for the layout of the code, the site doesn't appear to like my version of Opera :(
Edit:
Thanks guys, I've beed coding for about 6 hours straight and completely overlooked the incrementing, which is why I thought the \n remained still.
I also didn't know about the \r, uning Linux but trying to make cross platform so this is helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这个
try this
您在哪个操作系统上运行该程序? Windows 上的 \n 是两个字符 (\r\n) 。 如果您只想忽略换行符,则不需要第二个条件。
但另一个问题是您每次都会增加循环变量! 仅当向缓冲区添加内容时才应增加“循环”! 从 for(..) 中取出“loop++”并将其添加到 buffer[loop++] = c; 中。 最有可能的是,您在缓冲区中得到随机字符来代替 '\n':s,例如,它很可能是零。
Which operating system you are running this on? \n on Windows is two characters (\r\n) . If you only want to ignore newlines, the second condition is not needed.
But another problem is that you increment loop variable every time! You should increment 'loop' only when you add stuff to the buffer! Take 'loop++' away from for(..) and add it to buffer[loop++] = c;. Most likely you get random characters in the buffer in place of '\n':s, which can well be zeroes, for instance.