• Register
1 vote
24 views

Problem:

I am a new student of c++ and learning new things day by day.

Well, I have a text file containing thousands of lines possibly. I am willing to give them a count (if possible). What is the easiest and efficient way to get number of lines in a file c++? Please, keep it simple so that I can understand the code easily.
Thanks.

12 7 7
15,250 points

1 Answer

1 vote

Solution:

The line counting program is very useful in different fields. Please, find the code snippet below.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
 ifstream f;
   char ch;
   int numberchars, numberlines;
   f.open("Test.txt");
   numberchars = 0;
   numberlines = 0;
   f.get(ch);
   while (f) {
     while (f && ch != '\n') {
       numberchars = numberchars + 1;
       f.get(ch);
     }
     numberlines = numberlines + 1;
     f.get(ch);
   }
   cout << "The file has " << numberlines << " lines and " 
     << numberchars << " characters" << endl;
   return(0);
}

Note: I’ve added the code to find the characters too in this program.

13 9 6
94,240 points

Related questions

1 vote
1 answer 20 views
20 views
Problem: I have a python file that contains too many lines of code. I have written a code to count the total number of lines in a exact file. My code: def file_name(fname): with open(fname) as fn: for i, l in enumerate(fn): pass return i+1 Does the code give me the exact count ? If not how can I solve this?
asked Apr 5 LizzyM 6.1k points
1 vote
1 answer 13 views
13 views
Problem: Well, I have a text file containing thousands of lines possibly. I am willing to give them a count (if possible). What is the easiest and efficient way to write a program to get number of lines in a file python? Please, keep it simple so that I can understand the code easily. Thanks.
asked Mar 29 Gavin 15.3k points
0 votes
0 answers 2 views
2 views
I want to count lines, words and characters from a file. I'm having a problem counting the right amount of characters and words.
asked 18 hours ago Ahsan 1.6k points
0 votes
1 answer 22 views
22 views
Problem: I have recently started learning the C Programming. Currently I am trying to write C programs. In this coding problem I am trying to count the number of characters, newlines and number of words. But I think there is some issue in the second while loop which I am unable to ... ();                 nc++;             }             nc++;         }     }     printf("%d %d %d",nl,nc,nw); }
asked Jun 16 Raphael Pacheco 4.9k points
0 votes
1 answer 8 views
8 views
I have a question about how to display specific file lines defined in a file. First, here we have the file with the defined lines to display: (lineas.txt) 0 1 3 6 9 12 15 17 Here we have the file to show the specific lines: (file.c) //Arxiu.c #include <stdio.h> int main ... (token, sizeof (line), file2); puts (fgets (token, 1024, file2)); } return 0; } Thanks for your help, I hope you can help me.
asked Aug 7 game 4.3k points