c++ - 如何在 C++ 中使用 fstream get() 获取 int

标签 c++ file

我是 C++ 新手, 现在我要做的是创建一个文件,并将 int 值写入其中 然后我想用 get 函数获取这些 int 值!(这里异常(exception)的返回类型是 int ) 实际上这是一个索引文件,所以我要放入的都是int值! 但我发现fstream.put和fstream.get都只能操作char值。 那么有没有人愿意帮助我,如何做好我的工作。 这是我的代码

vector<int> tra1;
vector<int> tra2;
int last_capa = 0;
    for(int i=1;i<97;i++){
        output.put(tra1[i-1] * 5 + tra2[i-1] + last_capa);
        last_capa += (tra1[i-1] - 1) * 5 + tra2[i - 1];
    } 

下面是读取int的代码 这里我尝试获取一个int数来操作

vector<int> tra4
output.seekg(100);
unsigned int n = output.get() + tra4[2];

感谢您的帮助

浩然

最佳答案

除了 get 之外,您还可以使用 fstream 的运算符 >> 将文件中的值读取到 int 中。

fstream fs("input.txt", std::fstream::in); //input file
int k;
while(fs >> k)
{
   //do something with k
}
fs.close();

关于c++ - 如何在 C++ 中使用 fstream get() 获取 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831460/

相关文章:

android - 在 Android 上使用 FileOutputStream 创建的文件在哪里?

linux - 根据目录名称移动文件 (Linux/Debian/#!)

python - 如果 "a.pyc"文件存在则删除 "a.py"文件

c++ - C++0x 和 C++11 有什么区别?

c++ - 通过 fork() 使用共享内存

c++ - 在 C++ 中等效的 open(file, O_NONBLOCK)

带有两个参数的 C++ CPPUNIT_ASSERT

c# - 是否有 la Gavoille 等人的带有距离标记的最短路径算法的开源实现?

c# - 如何从 Process.Start 中抛出 FileNotFoundException

c# - 最终的 .NET 文件和目录实用程序库?