Examples C++

Read Strings from a File

In this C++ example, we demonstrate how to read a series of strings from a file. First, we create an input file object, which has the class type ifstream; The i stands for input, the f stands for file, and stream means that it accepts streams of data. In this case, the stream is a set of characters.

After we create the stream objeect, we open the file for reading. In general, streams can be opened for reading, writing, or both. Input streams are opened for reading by default. Finally, we read the four cardinal virtues and the three theological virtues from the file and close it.

And if any one loves righteousness, her labors are virtues; for she teaches self-control and prudence, justice and courage; nothing in life is more profitable for men than these. (Wisdom 8:7)

For now we see in a mirror dimly, but then face to face. Now I know in part; then I shall understand fully, even as I have been fully understood. So faith, hope, love abide, these three; but the greatest of these is love. (1 Corinthians 13:12-13)

Fortitude, Temperance, Faith, Charity, Hope, Justice, Prudence

Virtues.txt

Fortitude
Prudence
Justice
Temperance
Faith
Hope
Charity
 

main.cpp

#include <iostream>
#include <fstream>
#include <string>

int main() {
	// Read the string back from the file.
	std::cout << "Reading from the file:" << std::endl;
	std::ifstream qReadTextFile;
	qReadTextFile.open("Virtues.txt");
	// Read until we reach the end of the file
	std::string qString;
	while (qReadTextFile >> qString) {
		std::cout << qString << std::endl;
	}
	return 0;
}
 

Output

Reading from the file:
Fortitude
Prudence
Justice
Temperance
Faith
Hope
Charity
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.