Count the number of characters and the number of words in a TXT file

Source: Internet
Author: User

Exercise 2 Chapter 14
Write a program to count the number of characters and numbers of word in a file;
Author: Guo junling
Date: 2005.4.12
# Include <iostream>
# Include <fstream>
# Include <string>

Using namespace STD;

Int main ()
// Open the file as input
Ifstream in ("exercise3.txt", IOS: In );

// If opening fails, a prompt is displayed.
If (in. Fail ())
Cout <"fail on opening file" <Endl;
// Ch_count stores the number of characters and word_count stores string information. The value is initialized to 0.
Int ch_count = 0, word_count = 0;

// Ch_in_file temporarily stores characters read from files
Char ch_in_file;

// Read characters from the object continuously
While (in. Get (ch_in_file ))
Ch_count ++;

// Close the file
In. Close ();

Ifstream Word ("exercise3.txt", IOS: In );

// Word_file temporarily stores strings read from files
String word_file;

// Continuously read strings from files
While (in> word_file)
Word_count ++;

// Output the number of characters and strings respectively.
Cout <"No. of char in file:" <ch_count <Endl;
Cout <"No. of string in file:" <word_count <Endl;
Word. Close ();
Return 0;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.