按char读取字符串,直到C/C ++行结束 [英] Reading string by char till end of line C/C++

查看:147
本文介绍了按char读取字符串,直到C/C ++行结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何一次读取一个字符的字符串,并在到达行尾时停止?我正在使用fgetc函数从文件读取并将字符放入数组(后者会将数组更改为malloc),但是无法弄清楚到达行尾时如何停止

How to read a string one char at the time, and stop when you reach end of line? I'am using fgetc function to read from file and put chars to array (latter will change array to malloc), but can't figure out how to stop when the end of line is reached

对此进行了尝试(c是文件中带有char的变量):

Tried this (c is the variable with char from file):

if(c=="\0")

但是它给出了我无法将指针与整数进行比较的错误

But it gives error that I cant compare pointer to integer

文件看起来像(单词的长度未知):

File looks like (the length of the words are unknown):

one
two
three

因此出现了以下问题: 1)我可以将c与\ 0进行比较,因为\ 0是两个符号(\和0)还是被算作一个(与\ n相同的问题) 2)也许我应该使用\ n? 3)如果上述建议有误,您会提出什么建议(请注意,我必须同时读取字符串char).

So here comes the questions: 1) Can I compare c with \0 as \0 is two symbols (\ and 0) or is it counted as one (same question with \n) 2) Maybe I should use \n ? 3) If suggestions above are wrong what would you suggest (note I must read string one char at the time)

(请注意,我对C ++相当陌生(并且可以自行编程))

(Note I am pretty new to C++(and programming it self))

推荐答案

您要使用单引号:

if(c=='\0')

双引号()表示字符串,它是字符序列.单引号(')表示单个字符.

Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.

但是,行尾由换行符'\ n'表示.

However, the end-of-line is represented by the newline character, which is '\n'.

请注意,在两种情况下,反斜杠都不是字符的一部分,而只是表示特殊字符的一种方式.使用反斜杠可以表示各种不可打印的字符,也可以表示否则会使编译器感到困惑的字符.

Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.

这篇关于按char读取字符串,直到C/C ++行结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆