Reading string by char till end of line C/C++

user3102621 picture user3102621 · May 18, 2014 · Viewed 185.2k times · Source

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

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

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)

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

Answer

Vaughn Cato picture Vaughn Cato · May 18, 2014

You want to use single quotes:

if(c=='\0')

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

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.