c++将行getline放入数组中,用新行分隔

c++ getline into array, separated by new line

本文关键字:新行 分隔 数组 将行 getline c++      更新时间:2023-10-16

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

因此该文件类似于:

10
20
36

在这样的东西中阅读这篇文章将起作用:

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

或者,如果您对std-lib:感到满意

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,

到stdout。