C++ 显示二维阵列和stringstream中的数据
我正在编写一个程序,从一个文件中读取数据,该文件如下所示:C++ 显示二维阵列和stringstream中的数据,c++,arrays,fstream,stringstream,C++,Arrays,Fstream,Stringstream,我正在编写一个程序,从一个文件中读取数据,该文件如下所示: 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 使用stringstream解析这些字符(W、Y或Z),并将其存储在5x15的二维数组中。现在,我很难计算每行中每个字符出现的次数
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
使用stringstream
解析这些字符(W、Y或Z),并将其存储在5x15的二维数组中。现在,我很难计算每行中每个字符出现的次数。通过在函数中使用计数器变量,我尝试了多种方法来实现这一点,但到目前为止还没有实现。供参考,其想法是创建一份报告,显示每行的数据,然后显示所有行的总数
我怎样才能做到这一点呢?(我只能将数组用于此赋值(没有向量、结构或类))。谢谢各位
#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;
}
}
}
}
#包括
#包括
#包括
使用名称空间std;
void fromFile(ifstream&,char items[][15],const int,const int,char);
int main()
{
如果输入;
in.open(“file.txt”);
常量int A_行=5,A_列=15;
字符项[A_行][A_列];
详细信息;
fromFile(in、items、A_行、A_列、itemDetails);
in.close();
返回0;
}
void fromFile(ifstream&in,char items[][15],const int A_行,const int A_列,char itemDetails)
{
for(int rows=0;rows>项目详细信息)
{
项目[行][列]=项目详细信息;
//测试以正确显示文件中的所有数据
//cout我将使用一个简单的数组来解释所有的字母。
字母表有26个字母(a-z),因此我将创建一个长度为26的数组,其中每个位置代表一个字母。
然后,你可以通过从每个字母中减去“a”来找到每个字母在数组中的位置。它的工作原理很像一张地图
以下是一个片段:
int letters[26] = {0};
letters['z' - 'a'] += 1; // letters[25], or 26th element.
提示:列
和行
在从stringstream读取时不会递增。是否要求使用stringstream?如果没有它,则更容易:直接使用ifstream。首先解决问题的更简单版本。硬编码一行(例如“W Z W Y W Y W Y W Y W Y Z W Y Y Y Z Y”)并编写一个计算Ws数量的函数。@a.S.H使用stringstream并不是必需的。想想看。不要使用getline和stringstream,您只需要在>>项[行][列]
中使用即可。使用in.ignore()
来拒绝中间的空格。