I am new to C++ and trying to learn on my own. How do I go about setting up an array of strings?
Printable View
I am new to C++ and trying to learn on my own. How do I go about setting up an array of strings?
Code:
#include <string.h>
const int MaxStrings = 10; // constant global variable...
int main()
{
string ArrayOfStrings[MaxStrings]; // creates an array of 10
// strings...
return 0;
}
hope this helps...
matheo917
aren't you supposed to use header files without the .h whenever possible? (newest standard of C++).
you don't have to, --- the word "standard" doesn't force you to do so, and it won't hurt you if you don't...
but if you insist:
Code:
#include <iostream>
using namespace std;
matheo917
Thanks a bunch!
I will put it to use
Code:#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> MyStrArray; // Dynamically sized array of string objects.
// Insert some string objects into the array, it will grow as needed.
MyStrArray.push_back("dog"); // This is MyStrArray[0]
MyStrArray.push_back("cat"); // This is MyStrArray[1]
MyStrArray.push_back("turtle"); // This is MyStrArray[2]
MyStrArray.push_back("rabbit"); // This is MyStrArray[3]
// Output array of strings, one entry on each line.
vector<string>::iterator it;
for( it = MyStrArray.begin(); it != MyStrArray.end(); it++ )
cout << *it << endl;
return 0;
}
>>vector<string> MyStrArray;
Using typedefs is better, someties you encounter problems with using the std namespace and vector classes in the same program.
typedef std::vector<string> StringVector;