Reputation: 160
I'm writing a program that reads data from a file that looks like:
W Z W Y W Y W W Y W Y Z W Z Y
Z W W W Y W Y W Z Y W Z W Y Y
Z W Z Z Y Z Z W W W Y Y Y Z W
Z W Z Z Y Z Z W W W Y Y Y Z W
Z W Z Z Y Z Z W W W Y Y Y Z W
I'm storing these characters in a 2D array, and I need to get the total amount of Ws, Zs, and Ys on each line but my code is printing out the total for each letter across the entire file, instead of the total on each line:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream in;
in.open("file.txt");
const int A_ROWS = 5, A_COLUMNS = 15;
char items[A_ROWS][A_COLUMNS];
// load 2D array with contents from file.
for (int rows = 0; rows < A_ROWS; rows++)
{
for (int columns = 0; columns < A_COLUMNS; columns++)
{
in >> items[rows][columns];
}
}
//set counter for one letter
int W = 0;
for (int rows = 0; rows < A_ROWS; rows++)
{
for (int columns = 0; columns < A_COLUMNS; columns++)
{
if (items[rows][columns] == 'W')
{
W++;
}
}
}
cout << W; // this prints out the TOTAL amount of Ws in the entire file
in.close();
return 0;
}
How can I get the total of each letter per line? Thanks all.
Upvotes: 0
Views: 48
Reputation: 34199
So, you can simply move your W
output and reset to the outer loop:
//set counter for one letter
int W;
for (int rows = 0; rows < A_ROWS; rows++)
{
W = 0;
for (int columns = 0; columns < A_COLUMNS; columns++)
{
if (items[rows][columns] == 'W')
{
W++;
}
}
cout << "Row " << rows << ": " << W << endl;
}
Upvotes: 1
Reputation: 206607
How can I get the total of each letter per line? Thanks all.
Create three arrays to keep track of the counts of the letters in each line.
int wCounts[A_ROWS] = {0};
int yCounts[A_ROWS] = {0};
int zCounts[A_ROWS] = {0};
Keep the count of the letters in the arrays instead of in single variables.
For W
, it will be:
if (items[rows][columns] == 'W')
{
wCounts[rows]++;
}
Upvotes: 1