我开始编写C++,我正在尝试读取格式如下的文本文件:
32.0 12.43
503.2 3.212
Run Code Online (Sandbox Code Playgroud)
等等
在Java中,我可以使用Scannerwith .nextFloat(),并将contains放入Array.我试图用C++实现同样的目标.这是怎么做到的?
从标准输入读取
#include <iostream>
int main()
{
float f1, f2, f3, f4;
std::cin >> f1 >> f2 >> f3 >> f4;
}
Run Code Online (Sandbox Code Playgroud)
从文件中读取
#include <fstream>
int main()
{
std::ifstream fin("file.txt"); //fin is an arbitrary identifier
float f1, f2, f3, f4;
fin >> f1;
fin >> f2;
fin >> f3;
fin >> f4; // or fin >> f1 >> f2 >> f3 >> f4; no difference
}
Run Code Online (Sandbox Code Playgroud)
要将所有浮点数读入浮点数组(向量),可以使用:
#include <fstream>
#include <vector>
#include <iterator> //for istream_iterator and back_inserter
#include <algorithm> //for copy
int main()
{
std::ifstream fin("input.txt");
std::vector<float> v; //could also initialize with the two-iterator constructor
std::copy(std::istream_iterator<float>(fin),
std::istream_iterator<float>(),
std::back_inserter(v)); //push_back into vector
}
Run Code Online (Sandbox Code Playgroud)
阅读有关此处和其他地方的流输入/输出的更多信 我还强烈建议你阅读一本好的C++书
| 归档时间: |
|
| 查看次数: |
3372 次 |
| 最近记录: |