[英]How to input multiple values from a txt file into an array C++
我希望将 .txt 文件的各个输入输入到我的数组中,其中每个输入都用空格分隔。 然后计算这些输入。 如何将 .txt 文件中的多个值输入到我的数组中?
int main()
{
float tempTable[10];
ifstream input;
input.open("temperature.txt");
for (int i = 0; i < 10; i++)
{
input >> tempTable[i];
cout << tempTable[i];
}
input.close();
return 0;
}
根据我在这里写的内容,我希望文件的输入按照计划进行,每个值都输入 tempTable[i],但是当运行程序输出时,会出现极端数字,即 -1.3e9。
温度.txt文件如下:
25 20 11.2 30 12.5 3.5 10 13
您的文件包含 8 个元素,您迭代了 10 次。
您应该使用vector
或list
并迭代while(succeded)
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
float temp;
std::ifstream input;
input.open("temperature.txt");
std::vector<float> tempTable;
while (input >> temp)
{
tempTable.push_back(temp);
//print last element of vector: (with a space!)
std::cout << *tempTable.rbegin()<< " ";
}
input.close();
return 0;
}
您可以使用 boost::split 或直接将描述符分配给变量
std::ifstream infile("file.txt");
while (infile >> value1 >> value2 >> value3) {
// process value1, value2, ....
}
或者使用其他版本
std::vector<std::string> items;
std::string line;
while (std::getline(infile, line)) {
boost::split(items, line, boost::is_any_of(" "));
// process the items
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.