[英]Displaying data from 2d array and stringstream
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. 这些字符(W,Y或Z)使用的是解析stringstream
,并存储在一个2D阵列这是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;
}
}
}
}
I would use a simple array to account for all the letters. 我将使用一个简单的数组来说明所有字母。 The alphabet has 26 letters (az), so I would create an array with a length of 26 where each position represents a letter. 字母有26个字母(az),因此我将创建一个长度为26的数组,其中每个位置代表一个字母。 You can then find the position of each letter in the array by subtracting 'a' from each letter. 然后,您可以通过从每个字母减去“ a”来找到每个字母在数组中的位置。 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.