dan*_*uch 1 c++ java file-io ios
请注意,这不是一个"好于"的讨论.
我是一名Java程序员,它让我感到非常愚蠢,不知道如何做很多C++文件IO.
我需要为XML解析器制作非常简单的适配器,就像下面的代码所说的那样
在Java中,我可以使用:
BufferedReader reader = new BufferedReader(
new InputStreamReader(xmlInputStream));
String xml = "";
String line = null;
while ((line = reader.readLine()) != null) {
xml += line + "\n";
}
return xmlParser11.parse(xml);
Run Code Online (Sandbox Code Playgroud)
对我来说最大的问题是如何reader在C++中使用它
非常感谢!
编辑cutted;)
为了更温和地介绍,以下C++代码尽可能地模仿您的Java代码:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream xmlInputStream("input.xml"); // or istringstream or istream
std::string xml;
std::string line;
while(getline(xmlInputStream, line))
{
xml += line + "\n";
}
//return xmlParser11.parse(xml);
std::cout << xml << '\n';
}
Run Code Online (Sandbox Code Playgroud)
但是当然没有必要循环在C++中将输入流读入字符串:输入流可以表示为一对迭代器,可以以多种不同的方式使用:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
int main()
{
std::ifstream xmlInputStream("input.xml");
std::istreambuf_iterator<char> beg(xmlInputStream), end;
std::string xml(beg, end);
std::cout << xml << '\n';
}
Run Code Online (Sandbox Code Playgroud)
但是通常甚至不需要临时字符串对象:C++解析器可以直接在输入流或一对迭代器上操作.
| 归档时间: |
|
| 查看次数: |
3111 次 |
| 最近记录: |