打开一个文件并将数据放入双向量中,C++

Opening a File and putting the data into a double vector, C++

本文关键字:数据 向量 C++ 文件 一个      更新时间:2023-10-16

我是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;
    }

为了修改这些,我将执行以下操作:

  1. 我会删除string input[row][col]因为稍后会正确定义。
  2. 我会while (getline(file, line))更改为while (getline(file, line) && row < ROW)
  3. 我会把while (getline(iss, result, ','))改成while (getline(iss, result, ',') && col < COL)

我不保证这些是唯一的问题,也不保证在纠正这些问题后代码将完美运行。(我很少再用C++编程了,所以我不能100%自信地保证。但是,这些只是我立即注意到的一些初始错误/问题。


编辑:作为附加说明,我同意发布的另一个答案(现在似乎已删除),该答案建议将ROWCOL更改为预处理器定义/宏。例如,const int ROW = 10将变得#define ROW 10const int COL = 4将成为#define COL 4。在这里的示例中,它不会导致巨大的变化,但这里的好处是 ROWCOL 不会占用内存空间作为变量,因为编译器将分别用文字定义的值 4 和 10 替换对 COLROW 的所有引用。

不过,这在某种程度上是基于偏好的建议,所以请随意做任何你觉得更舒服的事情。仅根据您提供的代码片段,您可能不会看到任何性能变化。但是,我想对此发表我个人的看法,因为另一个答案提出了它。

至少需要删除第一个

string input[row][col];

毕竟,input被(正确)声明了几行。