0

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

4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by firstPerson
0

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

0

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]

Edited by Ancient Dragon: n/a

0

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?

0

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;
}

Edited by firstPerson: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.