使用C++读取格式化文件

Formatted file reading with C++

本文关键字:文件 格式化 读取 C++ 使用      更新时间:2023-10-16

我正在尝试从文件中读取所有整数并将它们放入数组中。我有一个包含以下格式的整数的输入文件:

3 74
74 1
1 74
8 76

基本上,每行包含一个数字,一个空格,然后是另一个数字。我知道在 Java 中我可以使用 Scanner 方法 nextInt(( 来忽略间距,但我在C++中没有找到这样的函数。

#include <fstream>
#include <iostream>
#include <vector>
int main()
{
  std::vector<int> arr;
  std::ifstream f("file.txt");
  int i;
  while (f >> i)
    arr.push_back(i);
}

或者,使用标准算法:

#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
  std::vector<int> arr;
  std::ifstream f("file.txt");
  std::copy(
    std::istream_iterator<int>(f)
    , std::istream_iterator<int>()
    , std::back_inserter(arr)
  );
}
int value;
while (std::cin >> value)
    std::cout << value << 'n';

通常,流提取程序会跳过空格,然后翻译后面的文本。

// reading a text file the most simple and straight forward way
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int main () {
int a[100],i=0,x;
  ifstream myfile ("example.txt");
  if (myfile.is_open())  // if the file is found and can be opened
  {
    while ( !myfile.eof() ) //read if it is NOT the end of the file
    {
      myfile>>a[i++];// read the numbers from the text file...... it will automatically take care of the spaces :-)
    }
    myfile.close(); // close the stream
  }
  else cout << "Unable to open file";  // if the file can't be opened
  // display the contents
  int j=0;
  for(j=0;j<i;j++)
   {//enter code here
    cout<<a[j]<<" ";                 
 }
//getch();
  return 0;
}