显示来自2d数组和字符串流的数据
Displaying data from 2d array and 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
这些字符(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.
相关文章:
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 如果我在块中编写字符串文字,是否会从数据部分复制整个字符串数据?
- 无法在 c++ 中将字符串分配给字符串数据类型
- 将特定字符串数据解析为变量
- C++ 将字符串数据包转换为 iphdr语言 - 字符串数据包的格式应该是什么?
- 基于给定字符串数据类型的链表删除节点
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 使用来自串行端口的字符串数据来操作振镜扫描仪在更高的速度下会出错
- 将元音与字符串数据类型的字符串分开,并将其存储在新字符串中
- 放置在外部 DLL 中的类中的字符串数据的内存损坏
- 创建字符串数据串起
- 如何在C++中将字符串数据存储在字符串 2D 数组中
- C++程序不返回文件中文本和字符串数据的值
- C++:在字符串数据类型中创建单词"letter after letter"
- 将向量中的字符串数据解析为适当的数据类型 c++
- 如何将提取的字符串数据转换为字符数组
- 字符串数据类型变量初始化
- 如何从本机空间中的宗地中检索字符串数据
- 在C 中使用字符串数据类型的问题