I am new in VC++. As to modify a software,I have to read contents of an .xml file. From this data I have to manipulate further, While I tried it by copying to a CString, it reads by word by word(cuts at spaces). But I need at least a line by line need. plz help me...

Dani AI

Generated

Short answer: the behavior you described (strings split at spaces) comes from using formatted extraction (operator>>), which tokenizes on whitespace. For simple line-by-line reads use the standard C++ stream helper std::getline. If you need the whole file as one string, read the stream buffer. For real XML work, use an XML parser instead of ad-hoc string splitting.

As pointed out, a parser prevents fragile, tag- and-attribute bugs; as suggested, prefer standard streams for reading input. Quick examples:

Read file line-by-line (preserves spaces inside a line):

#include <fstream>
#include <string>

std::ifstream in("file.xml");
if (!in) /* handle error */;
std::string line;
while (std::getline(in, line)) {
    // line contains the full text up to newline
    // convert to CString if your MFC code requires it:
    // CString cs(line.c_str());  (ANSI builds) or convert for Unicode builds
}

Read entire file into one std::string (keeps all whitespace):

#include <fstream>
#include <iterator>
#include <string>

std::ifstream in("file.xml", std::ios::binary);
std::string contents((std::istreambuf_iterator<char>(in)),
                     std::istreambuf_iterator<char>());

Practical cautions: check file encoding and BOM—XML may be UTF-8 or UTF-16; reading raw bytes into std::string may require conversion to wide strings for Unicode/Unicode builds in VC++. If you must interpret elements/attributes, use a tested XML library (TinyXML-2, pugixml, MSXML). For reference, see the standard std::getline behavior on cppreference and TinyXML-2 on GitHub: std::getline tinyxml2.

If the original code used extraction like in >> someCString; change it to std::getline, or use a parser for robust XML handling.

Recommended Answers

All 2 Replies

I would also ditch the MFC file handling classes such as CFile and CArchive, but use normal standard c++ fstreams and std::string, which are a whole lot easier to use. That assumes you are using a compiler that supports fstreams and std::string -- some embedded compilers do not.

commented: Compilers that don't support fstream == fail! X_X +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.