【发布时间】:2021-04-15 02:36:33
【问题描述】:
我有以下 c++ 代码,我通过它从 .txt 文件中读取值
能否请您帮助我改进代码,以便我不仅可以从 .txt 中读取 14 个值,还可以读取 n 个值
//reading from text file
static std::vector<double> vec;
double a[14]; //values got read from txt file
int i = 0;
void readDATA()
{
double value;
std::ifstream myFile;
myFile.open("filename.txt", std::ios::app);
if (myFile.is_open())
{
std::cout << "File is open." << std::endl;
while (myFile >> value)
{
vec.push_back(value);
std::cout << "value is " << value << std::endl;
a[i] = value;
std::cout << "a" << i << "=" << a[i] << std::endl;
i = i + 1;
}
myFile.close();
}
else
std::cout << "Unable to open the file";
}
.txt 文件看起来像
0 0 40 45 15
0 1 40 -45 10
0 0 180 90 15
【问题讨论】:
-
增加
i后,您可以添加if ( i == n) break;,假设您有一个n变量并且n 大于0。 -
@drescherjm 感谢您的评论,但是我应该如何设置 a[] 呢?!能否请您进一步澄清一下
-
我什至不知道为什么你有一个
a变量,所以很难建议如何处理它。 -
没错,a没用
标签: c++ string stream ifstream ofstream