Displaying data from 2d array and stringstream

こ雲淡風輕ζ 提交于 2019-12-25 03:40:08

问题


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 

These characters (W, Y, or Z) are parsed using a stringstream and stored in a 2D array that's 5x15. Now I'm having trouble counting the amount of times that each character appears on each line. I've tried multiple ways of achieving this by using counter variables in my function but I haven't gotten it so far. FYI, the idea is to then create a report to display this data for each line and then a total for all.

How can I achieve this then? (I can only use arrays for this assignment (no vectors, structures, or classes)). Thanks guys.

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

void fromFile(ifstream &, char items[][15], const int, const int, char);

int main() 
{
    ifstream in;
    in.open("file.txt");

    const int A_ROWS = 5, A_COLUMNS = 15;

    char items[A_ROWS][A_COLUMNS];
    char itemDetails;

    fromFile(in, items, A_ROWS, A_COLUMNS, itemDetails);

    in.close();
    return 0;
}

void fromFile(ifstream & in, char items[][15], const int A_ROWS, const int A_COLUMNS, char itemDetails)
{
    for (int rows = 0; rows < A_ROWS; rows++)
    {
        for (int columns = 0; columns < A_COLUMNS; columns++)
        {
            string theData = "";
            if (getline(in, theData))
            {
                stringstream str(theData);
                while (str >> itemDetails)
                {
                    items[rows][columns] = itemDetails;
                    // test to display all the data from the file properly
                    // cout << items[rows][columns] << " ";
                }
                cout << endl;
            }
        }
    }
}

回答1:


I would use a simple array to account for all the letters. The alphabet has 26 letters (a-z), so I would create an array with a length of 26 where each position represents a letter. You can then find the position of each letter in the array by subtracting 'a' from each letter. It would work pretty much like a map.

Here is a snippet:

int letters[26] =  {0};
letters['z' - 'a'] += 1; // letters[25], or 26th element.


来源:https://stackoverflow.com/questions/33600984/displaying-data-from-2d-array-and-stringstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!