How to read integer value from file in C++

↘锁芯ラ 提交于 2019-12-11 03:19:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!