问题
How can read integer value from file? For example, these value present in a file:
5 6 7
If I open the file using fstream
then how I can get integer value?
How can read that number and avoid blank space?
回答1:
It's really rare that anyone reads a file Byte by Byte ! ( one char has the size of one Byte).
One of the reason is that I/O operation are slowest. So do your IO once (reading or writing on/to the disk), then parse your data in memory as often and fastly as you want.
ifstream inoutfile;
inoutfile.open(filename)
std::string strFileContent;
if(inoutfile)
{
inoutfile >> strFileContent; // only one I/O
}
std::cout << strFileContent; // this is also one I/O
and if you want to parse strFileContent you can access it as an array of chars this ways: strFileContent.c_str()
回答2:
ifstream file;
file.open("text.txt");
int i;
while (file >> i) {
cout << i << endl;
}
回答3:
ifstream f(filename);
int x, y, z;
f >> x >> y >> z;
回答4:
ifstream f;
f.open("text.txt");
if (!f.is_open())
return;
std::vector<int> numbers;
int i;
while (f >> i) {
numbers.push_back(i);
}
来源:https://stackoverflow.com/questions/4827301/how-to-read-integer-value-from-file-in-c