【问题标题】:c++ getline into array, separated by new line [closed]c ++ getline进入数组,由新行分隔[关闭]
【发布时间】:2013-07-03 14:41:34
【问题描述】:

基本上我有一个文本文件,其中的数字由新行分隔。我想将每个数字输入到一个数组中,当新行带有一个新数字时,该新数字应该插入到数组中的下一个插槽中

【问题讨论】:

  • 问题是什么?

标签: c++ arrays getline


【解决方案1】:

所以文件是这样的:

10
20
36

以这样的方式阅读它会起作用:

std::ifstream file {"file_name"};
int t;
std::vector<int> nums;
while(file >> t) 
   numes.push_back(t);

或者,如果您对标准库感到满意:

std::ifstream file {"file_name"};
std::vector<int> nums {
  std::istream_iterator<int> { file },
  std::istream_iterator<int> {      }
};

之后如下:

for(int n : nums) 
    std::cout << n ", ";

将打印

10, 20, 36,

到标准输出。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多