请注意,这不是一个“比”更好的讨论。
我是一名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);对我来说最大的问题是在C++中如何处理这个reader
非常感谢!
编辑裁切;)
发布于 2011-04-20 22:17:34
为了给出一个更温和的介绍,下面的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';
}当然,在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';
}但通常甚至不需要临时字符串对象: C++解析器可以直接对输入流或一对迭代器进行操作。
发布于 2011-04-20 21:54:17
如果你正在读取一个文件,你可以这样做:
std::ifstream file("myfile.xml");
std::stringstream xml;
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(),
std::ostream_iterator<char>(xml));这会将整个文件读取到std::stringstream xml中,包括换行符和所有内容(就像您的示例代码中一样)。然后,您可以使用xml.str()将其作为std::string访问。
发布于 2011-04-20 21:50:47
这是在使用STL --你是想问关于C++的问题,还是想要C语言的等价物(比如使用fopen,fread等)?
// main.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
string xml;
ifstream myfile("example.txt");
if( myfile.is_open() ) {
while( myfile.good() ) {
getline (myfile,line);
xml += line + "\n";
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}https://stackoverflow.com/questions/5731312
复制相似问题