[英]Formatted file reading with C++
I am trying to read all integers from a file and put them into an array. 我试图从文件中读取所有整数并将它们放入数组中。 I have an input file that contains integers in the following format:
我有一个包含以下格式的整数的输入文件:
3 74
74 1
1 74
8 76
Basically, each line contains a number, a space, then another number. 基本上,每行包含一个数字,一个空格,然后是另一个数字。 I know in Java I can use the Scanner method nextInt() to ignore the spacing, but I have found no such function in C++.
我知道在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);
}
Or, using standard algorithms: 或者,使用标准算法:
#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';
In general, stream extractors skip whitespace and then translate the text that follows. 通常,流提取器会跳过空格,然后翻译后面的文本。
// 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.