RSS Subscription
Linux Howtos & Tutorials

Enter your email:

Delivered by


NOTE:New tutorials are from LinuxCareer.com

Poll

Do you own or wish to have iPhone?
 


Linux eBooks FREE Download
A guide to programming Linux kernel modules
Introduction to Linux - A Hands on Guide
A Newbie's Getting Started Guide to Linux

Linux from Scratch - Create Your Own Linux System - Free eBook

Linux: The Hacking Solution (v.3.0)

SQLite 3 with PHP Essential Training – Free Video Training Tutorials

This guide will introduce you to the world of GNU/Linux

The GNU/Linux Advanced Administration

A Complete Beginner's Manual for Ubuntu 10.04 (Lucid Lynx)

Advanced Bash-Scripting Guide

Set up, maintain, and secure a small office email server

Partner Linux Sites:
How-To.LinuxCareer.com
Jobs.LinuxCareer.com
TuxMachines
Monsterb
LinuxBloggers
AdamsInfo
LinuxScrew
All For Linux

C++ code on how to read characters from a file

Here is a small example of C++ code on how to read a characters from a file as well as to count the number lines of any particular file consist of. The code will check for "\n" the "new line character" and increase the number of lines stored in number_of_lines integer variable. Every iteration will also print single character including "\n" to an output.
First create a file called my-input-file.txt which will contain some text. For example:

welcome to
linuxconfig.org
c++

Then copy c++ code below to a file called read-characters.cpp:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

ifstream fin;
fin.open("my-input-file.txt", ios::in);

char my_character ;
int number_of_lines = 0;

while (!fin.eof() ) {

fin.get(my_character);
cout << my_character;
if (my_character == '\n'){
++number_of_lines;
}
}
cout << "NUMBER OF LINES: " << number_of_lines << endl;

}

and compile it with:

g++ read-characters.cpp -o read-characters

Execute new compiled binary file:

./read-characters

NOTE: your text file must be located in the same directory as your executable read-characters program.

NOTE: while loop and fin.get will add extra new line character so you may start with :

int number_of_lines = -1

OUTPUT:

welcome to
linuxconfig.org
c++

NUMBER OF LINES: 4

Share this linux post:

Submit C++ code on how to read characters from a file in Delicious Submit C++ code on how to read characters from a file in Digg Submit C++ code on how to read characters from a file in FaceBook Submit C++ code on how to read characters from a file in Google Bookmarks Submit C++ code on how to read characters from a file in Stumbleupon Submit C++ code on how to read characters from a file in Technorati Submit C++ code on how to read characters from a file in Twitter
 
Comments for this page are closed !!!
Please visit our new Linux Forum for additional help or discussion.


Linux eBooks FREE Download