提问人:Rawley Fowler 提问时间:12/2/2019 最后编辑:Rawley Fowler 更新时间:12/2/2019 访问量:856
如何将多个值从 txt 文件输入到数组 C++ 中
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
答:
0赞
camp0
12/2/2019
#1
您可以使用 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
}
1赞
SHR
12/2/2019
#2
您的文件包含 8 个元素,您迭代 10 次。
您应该使用 or 和 迭代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;
}
评论