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

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

You want to use single quotes:

if(c==)

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.

The answer to your original question

How to read a string one char at the time, and stop when you reach end of line?

is, in C++, very simply, namely: use getline. The link shows a simple example:

#include <iostream>
#include <string>
int main () {
  std::string name;
  std::cout << Please, enter your full name: ;
  std::getline (std::cin,name);
  std::cout << Hello,  << name << !n;
  return 0;
}

Do you really want to do this in C? I wouldnt! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You dont know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.

C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.

Your later questions regarding and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that its not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.

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

If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example

unsigned int count = 0;
while ( 1 )
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == n )
   {
      printF( The length of the line is %un, count );
      count = 0;
      if ( c == EOF ) break;
   }
   else
   {
      ++count;
   }
}    

or maybe it would be better to rewrite the code using do-while loop. For example

unsigned int count = 0;
do
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == n )
   {
      printF( The length of the line is %un, count );
      count = 0;
   }
   else
   {
      ++count;
   }
} while ( c != EOF );

Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.

But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.

Leave a Reply

Your email address will not be published.