Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading string by char till end of line C/C++ [duplicate]

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))

like image 235
user3102621 Avatar asked May 18 '14 20:05

user3102621


2 Answers

A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

if (c == '\n')

like image 154
ScottMcP-MVP Avatar answered Nov 15 '22 17:11

ScottMcP-MVP


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.

like image 41
Vaughn Cato Avatar answered Nov 15 '22 15:11

Vaughn Cato