c++从文件中一个一个地获取值

标签 c++ ifstream

我知道这类问题在 stackoverflow 上出现过很多次,但是我找不到适合我的问题的答案。我试图弄清楚如何从 C++ 中的文件中一个一个地获取值。让我解释一下:

test.txt

1 1 0.5
31 5 14

我想将 1,1,0.5 存储在我的 vector 或数组中并对其进行一些处理,然后获取第二行并再次进行相同的操作。有人可以帮助我吗?提前致谢。

最佳答案

C++实现方式:

#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>

int main()
{
   std::string line;
   std::ifstream ifs("test.txt");

   while ( std::getline( ifs, line ) ) {
      std::istringstream is( line );
      std::vector<double> numbers = std::vector<double>
                               ( std::istream_iterator<double>(is),
                                 std::istream_iterator<double>());
      //... f(numbers);
      // i.e:
      // std::copy( numbers.begin(), numbers.end(), 
      //            std::ostream_iterator<double>( std::cout, " "));
   }
}

关于c++从文件中一个一个地获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024276/

相关文章:

C++ 将隐式构造限制为特定值

c# - 将结构(或类)从 C++ dll 传递到 C# (Unity 3D)

c++ - 从文件中读取不正确的数据(C++、fstream)

c++ - 绑定(bind)方法给出错误 10038 (WSAENOTSOCK)

c++ - 检查 R 函数是否依赖于 C/C++ 编译代码的函数?

c++ - 在这种情况下应该使用 C++ 模板吗?

c++ - seekg 和 tellg 不兼容

c++ - 这种方法会涉及内存重新分配从而影响其效率吗?

c++ - 如何在C++中读取文件?

C++ 打开文件并向类对象输入数据