显示来自2d数组和字符串流的数据

Displaying data from 2d array and stringstream

本文关键字:字符串 数据 数组 2d 显示      更新时间:2023-10-16

我正在编写一个程序,从一个看起来像的文件中读取数据

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 

这些字符(W、Y或Z)使用stringstream进行解析,并存储在5x15的2D数组中。现在我在计算每个字符出现在每行上的次数时遇到了问题。通过在函数中使用计数器变量,我尝试了多种方法来实现这一点,但到目前为止还没有实现。仅供参考,我们的想法是创建一个报告,显示每行的数据,然后显示所有数据的总和。

那么我该如何实现呢?(我只能使用数组进行此赋值(没有向量、结构或类)。谢谢大家。

#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;
            }
        }
    }
}

我会使用一个简单的数组来说明所有的字母。字母表有26个字母(a-z),所以我会创建一个长度为26的数组,其中每个位置代表一个字母。然后,您可以通过从每个字母中减去"a"来找到数组中每个字母的位置。它的工作原理很像地图。

以下是一个片段:

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