For reading from an xml file,

char s[6];
ifstream x("output.xml");
x.getline(s,34);

char s[6];
I don't want to specify the maximum number of characters in 's'.So,I tried to use string s instead,but getline only takes character arrays.
When I used char*,it said,The variable 's' is being used without being initialized.
So,how do I use a character array that has no maximum number of characters(limit)??????

Dani AI

Generated

This thread shows the classic C vs C++ buffer problem. used a fixed C array and then an uninitialized char*, which leads to undefined behaviour because a raw pointer does not own or allocate storage. 's advice to use the C++ string-based API is the right direction: prefer owning, resizable types over manual buffers whenever possible.

Practical tips not shown above:

  • A char* must point to valid memory (stack array, new[], malloc, or an existing buffer). Failing that causes crashes or silent corruption.
  • std::string manages allocation for you and is the safe default for reading unknown-length text. Pre-allocating with reserve() can reduce reallocations for very long lines. Always check the file opened successfully before reading and handle EOF/IO errors.
  • For XML specifically, line-oriented reads are brittle: tags, attributes, CDATA, or pretty-printed XML can span lines. If the goal is to parse or extract elements, use a purpose-built XML library (TinyXML-2 or pugixml) rather than ad hoc string parsing. For very large files, prefer a streaming/sax-style parser to avoid loading everything into memory.

Further reading:

Recommended Answers

All 2 Replies

The <string> header provides a global that does what you need i.e. it works with std::string .
For example

#include <string>
#include <fstream>
#include <iostream>
int main()
{
  std::ifstream ifs("file.txt");
  std::string s;

  while(getline(ifs, s))
  {
    std::cout << s << std::endl;
  }

  return 0;
}

Thanks a lot!

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.