In C++, how do I read a txt file then count how many columns and how many rows i
ID: 3561606 • Letter: I
Question
In C++, how do I read a txt file then count how many columns and how many rows in the text?
Here's what I have so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string fname, line;
ifstream ifs; // input file stream
int i;
cout << "---- Enter a file name : ";
while (getline(cin, fname)) { // Ctrl-Z/D to quit!
// tries to open the file whose name is in string fname
ifs.open(fname.c_str());
if (ifs.fail()) {
cerr << "ERROR: Failed to open file " << fname << endl;
ifs.clear();
} else {
i = 1;
while (getline(ifs, line))
cout << "Number of Rows: " << i++<< endl;
ifs.close();
}
cout << "---- Enter another file name : ";
}
return 0;
}
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string fname, line;
ifstream ifs; // input file stream
int i;
cout << "---- Enter a file name : ";
while (getline(cin, fname)) { // Ctrl-Z/D to quit!
// tries to open the file whose name is in string fname
ifs.open(fname.c_str());
if (ifs.fail()) {
cerr << "ERROR: Failed to open file " << fname << endl;
ifs.clear();
} else {
i = 1;
while (getline(ifs, line)) {
//Finding columns in each row
//Treating each character as 1 column - If your requirment is a word seperated by space change according to it
int columns = line.length();
cout << "Row: "<< i << " Columns: " << columns << endl;
i++;
}
cout << "Total Number of Rows: " << i++<< endl;
ifs.close();
}
cout << "---- Enter another file name : ";
}
return 0;
}