打开一个文件并将数据放入双向量中,C++
Opening a File and putting the data into a double vector, C++
我是C++初学者,在我的程序开始时,我试图将csv文件中的数据输入到双向量中。
但是,当我尝试运行该程序时,我不断得到"行"和"col"未在此范围内声明。
我试图通过放置" int row; int col;'在"字符串输入 [行][col];"上方 尝试解决问题。
但是随后我收到错误"数组绑定不是']'标记之前的整数常量"。
我想知道如何解决这个问题?或者,如果也许我错过了一些我没有意识到的东西。
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
string input[row][col];
const int ROW = 10;
const int COL = 4;
string input[ROW][COL];
const string datatable = "table2.csv";
string line;
int col = 0;
int row = 0;
void readCSV() ////this is the function to read the file
{
ifstream file(datatable); ///opens file
while (getline(file, line))
{
istringstream iss(line); //takes out white
string result;
while (getline(iss, result, ','))
{
input[row][col] = result; // creates string for element
col = col + 1;
}
row = row + 1;
col = 0;
}
我希望
你不要认为这是冒犯性的,但这里有多个错误。
我将首先注释您的代码以显示错误所在,然后我将解释问题:
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
string input[row][col]; /* <- "row" and "col" are not yet defined */
const int ROW = 10;
const int COL = 4;
string input[ROW][COL]; /* <- you already have a variable named "input" */
const string datatable = "table2.csv";
string line;
int col = 0;
int row = 0;
void readCSV()
{
ifstream file(datatable); ///opens file
while (getline(file, line)) /* <- no check to make sure max rows are not exceeded */
{
istringstream iss(line); //takes out white
string result;
while (getline(iss, result, ',')) /* No check to make sure max columns are not exceeded */
{
input[row][col] = result; // creates string for element
col = col + 1;
}
row = row + 1;
col = 0;
}
为了修改这些,我将执行以下操作:
- 我会删除
string input[row][col]
因为稍后会正确定义。 - 我会
while (getline(file, line))
更改为while (getline(file, line) && row < ROW)
- 我会把
while (getline(iss, result, ','))
改成while (getline(iss, result, ',') && col < COL)
我不保证这些是唯一的问题,也不保证在纠正这些问题后代码将完美运行。(我很少再用C++编程了,所以我不能100%自信地保证。但是,这些只是我立即注意到的一些初始错误/问题。
编辑:作为附加说明,我同意发布的另一个答案(现在似乎已删除),该答案建议将ROW
和COL
更改为预处理器定义/宏。例如,const int ROW = 10
将变得#define ROW 10
,const int COL = 4
将成为#define COL 4
。在这里的示例中,它不会导致巨大的变化,但这里的好处是 ROW
和 COL
不会占用内存空间作为变量,因为编译器将分别用文字定义的值 4 和 10 替换对 COL
和 ROW
的所有引用。
不过,这在某种程度上是基于偏好的建议,所以请随意做任何你觉得更舒服的事情。仅根据您提供的代码片段,您可能不会看到任何性能变化。但是,我想对此发表我个人的看法,因为另一个答案提出了它。
至少需要删除第一个
string input[row][col];
毕竟,input
被(正确)声明了几行。
相关文章:
- 很好的语法来获取对向量/数组数据的大小引用?
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 如何以"union-like"方式更改C++向量的数据类型
- 在线程函数中处理数据向量时进行线程竞速
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 初始化可变数据结构中的共享指针向量
- 如何使用模板获取向量中的数据类型?
- 从自定义数据类型向量中删除重复元素
- C++:自定义数据类型向量错误的队列
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 如何有效地实现将向量的数据分配给多个变量?
- 如何从多维向量中提取数据
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 向量中的数据何时释放
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 如何高效更改向量中所有对象的成员数据?
- 使用算法查找自定义数据向量中的最大值和最小值
- 从逗号分隔的文本文件中创建有意义的数据向量的最佳方法是什么?
- 为什么清除后我仍然可以访问数据向量