I was wondering whether it was possible to use dynamic memory or something else to achieve something to the effect of entering numbers or a string using standard input without first having to specify how many instances you intend to enter. If this can be done through some other method please point me to a good resource to learn about it or post some code snippets. Thanks,
AspiringCoder

Recommended Answers

All 5 Replies

The string class and all of the STL container classes grow dynamically. What are you trying to do that those classes cannot accomplish.

There are lots of ways to do it -- which one you use will depend on the data you want. std::string is a c++ class that manages chracter arrays and expands/contracts it on demand. vector, list, set, and map manage arrays or lists of objects, and also expand/contract on demand. Fially you could roll your own for any of the previously mentioned, but that involves a lot of work on your part and is very error-bug prone, which is the reason they are in the c++ language.

[edit]^^ Sorry Edward I didn't see your post.[/edit]

Ok, say you are using an array to capture input but, you don't want to make the user input a number of values they will give. Insted you want to allow the user to enter a value, press enter, enter a value, press enter... until they enter a set value, say done. Would you need to use dynamic memory or something else?

As we said before you could use any of the STL containers.

Here is an example :

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(){
 vector< string > names;
 const string END = "!";
 cout << "Enter many names... <enter '" << END << "' to quit >\n";
 while(true){
  string temp;
  cin >> temp;
  if(temp != END)
    names.push_back(temp); //add names
  else break;
 }

  for(int i = 0; i < names.size(); ++i){
   cout << names[i] << "\n";
  }

  return 0;
}
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.