C++ Programming Code Examples
C++ > Code Snippets Code Examples
Use eof() to read and display a text file.
/* Use eof() to read and display a text file. */
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
char ch;
ifstream fin("text.txt");
if(!fin) {
cout << "Cannot open file.\n";
return 1;
}
do {
fin.get(ch);
if(!fin.eof() && (fin.fail() || fin.bad())) {
cout << "Input Error\n";
fin.close();
return 1;
}
if(!fin.eof()) cout << ch;
} while(!fin.eof());
fin.clear();
fin.close();
if(!fin.good()) {
cout << "Error closing file.";
return 1;
}
return 0;
}
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Get characters. Extracts characters from the stream, as unformatted input. The get() function is used to read a character(at a time) from a file. The classes istream and ostream define two member functions get(), put() respectively to handle the single character input/output operations. There are two types of get() functions. Both get(char *) and get(void) prototype can be used to fetch a character including the blank space,tab and newline character. The get(char *) version assigns the input character to its argument and the get(void) version returns the input character. Since these functions are members of input/output Stream classes, these must be invoked using appropriate objects.
Check whether either failbit or badbit is set. Returns true if either (or both) the failbit or the badbit error state flags is set for the stream. At least one of these flags is set when an error occurs during an input operation. failbit is generally set by an operation when the error is related to the internal logic of the operation itself; further operations on the stream may be possible. While badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is attempted on the stream. badbit can be checked independently by calling member function bad. This function does not accept any parameter. Function returns true if badbit and/or failbit are set.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Check whether state of stream is good. Returns true if none of the stream's error state flags (eofbit, failbit and badbit) is set. ios::good() and ios::bad() functions in C++ are used to check the state of the stream whether it is good or bad to do our task. Both of these are defined in ios library. The good() method of ios class in C++ is used to check if the stream is good enough to work. It means that this function will check if this stream has raised any error or not. Notice that this function is not the exact opposite of member bad, which only checks whether the badbit flag is set. This function does not accept any parameter. Function returns true if none of the stream's state flags are set.
Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream. Note that the value returned by this function depends on the last operation performed on the stream (and not on the next). Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.
Check whether badbit is set. Returns true if the badbit error state flag is set for the stream. The bad() method of ios class in C++ is used to check if the stream is has raised any bad error. It means that this function will check if this stream has its badbit set. This method does not accept any parameter. Function returns true if the stream's badbit error state flag is set. false otherwise.
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Set error state flags. Sets a new value for the stream's internal error state flags. The clear() method of ios class in C++ is used to change the current state of the specified flag by setting it. Hence this function changes the internal state of this stream. The current value of the flags is overwritten: All bits are replaced by those in state; If state is goodbit (which is zero) all error flags are cleared. In the case that no stream buffer is associated with the stream when this function is called, the badbit flag is automatically set (no matter the value for that bit passed in argument state). Note that changing the state may throw an exception, depending on the latest settings passed to member exceptions.
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is: • ofstream: This data type represents the output file stream and is used to create files and to write information to files. • ifstream: This data type represents the input file stream and is used to read information from files. • fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
C++ Program to find edge connectivity of a graph. An edge in an undirected connected graph is a bridge if removing it disconnects the graph. For a "disconnected undirected"
Displaying the "Topological Sort Method" of finding whether a given graph contains cycle or not using Kosaraju's Algorithm. Enter the source and destination. Cycles exist in graph.
Algorithm finds the median of 2 sorted arrays using binary search approach. Takes the input of 'n' Data Elements of both the arrays. Using decrease, conquer method find the combined