gpt4 book ai didi

c++ - 查找文本文件中的行数,并使用此维度构建数据点

转载 作者:行者123 更新时间:2023-11-30 03:59:18 25 4
gpt4 key购买 nike

这是直接来 self 的程序的代码。

 // count how many lines the read text document has, so the datastructure can have the correct dimension.
int number_of_lines = 0;
std::string line;
while (getline(myfile, line)) {
++number_of_lines;
}
std::cout << "Number of lines in text file: " << number_of_lines;
// the first line won't have a new line before it, so add one to number_of_lines
rows = number_of_lines + 1;
return 0;
}

// create a data point structure with "rows" number of rows
datapoint mypoints[rows];

[行]下方有一条红色波浪线,表示:

double rows Error: expression must have a constant value.

值不应该是常量,因为添加到 number_of_lines 的 while 循环在行使用 number_of_lines 之前完成?

最佳答案

您不能在 C++ 中创建可变长度数组 (VLA)。

datapoint mypoints[rows];
// ^^^^
// this is a variable (i.e. not a compile-time constant)

你可以做的是创建一个动态数组:

datapoint* mypoints = new datapoint[rows];
// ...
delete [] mypoints;

或者使用 vector :

std::vector<datapoint> mypoints(rows); // will default-construct all of them

关于c++ - 查找文本文件中的行数,并使用此维度构建数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26972695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com