我可以基于char *而不是文件创建std :: ifstream吗? [英] Can I create an std::ifstream based on a char* rather than a file?
问题描述
我对在Java和C ++之间共享数据感兴趣,因此对JNI感兴趣.当前,所有C ++代码都希望有一个文件,因此,所有文件均以std :: ifstream的形式编写.与其编写文件并再次读取它们,不如只是传递一个char *并让应用程序从中读取内容,而不是以某种方式将char *视为ifstream.无论如何,有没有创建基于char *的ifstream?
I am interested in sharing data between Java and C++ so JNI. Currently all the C++ code expects a file so its all written in terms of std::ifstream. Rather than writing the files and reading them again, I would like to be able to just pass a char* over and have the application read from that instead somehow treating the char* as a ifstream. Is there anyway to create a ifstream that is based on a char* ?
谢谢
推荐答案
是的,它称为std::istringstream
.您可以像这样使用它:
Yes, it's called std::istringstream
. You can use it like this:
#include<sstream>
....
char const* s = "whatever";
std::istringstream iss(std::string(s));
int i;
iss >> i;
....
如果您的代码期望特定的std::ifstream
,则可以将其更改为期望通用的std::istream
,正如Adrian所说,这两个都可以继承.
If your code expects a std::ifstream
specifically, you could change it to expect a generic std::istream
, from which both inherit, as Adrian mentioned.
这篇关于我可以基于char *而不是文件创建std :: ifstream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!