In c++, how to store different strings in an array?

for example, storing names in an array like this:

string name[ ]={ bob, mary, calvin};

is it correct?
after that how do i output ALL the 3 names? when i put:

cout << *name;

it only shows bob. sorry i am bad at array. pls help.. thanks
That should be with quotes: string name[ ]={ "bob", "mary", "calvin"};
For accessing the value you can use sub-scripting:
cout << name[0] << name[1] << name[2];
name[0] is "bob", name[1] is "mary" and name[2] is "calvin"


http://www.cplusplus.com/doc/tutorial/arrays.html
thanks! but u mind helping me out further? i want to put "Ron" in front of "John" and "Bob" after "Ram".. i have been doing ages and still can't solve it.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<string> vectA;
vector<int>::iterator it;

string name[]={"John", "Betty", "Ram"};

for (int i=0; i<3; i++)
{
vectA.push_back(name[i]);
cout << vectA[i] << " ";
}

vectA.insert(vectA.begin(), "Ron");
vectA.end();
vectA.push_back("Bob");
cout << vectA << " ";
}
Your code is right, you just don't need the vectA.end() call.
still got errors... =(
Which errors?
i dunno. it cannot run. there are a total of 26 errors when compile.

however there is a red flag at cout << vectA << " ";

You have to provide a << operator for that or just use a simple loop.

eg:
1
2
for(vector<string>::size_type i=0; i<vectA.size(); ++i)
   cout << vectA[i] << ' ';
um.. ok i try.. i managed to solve it without errors using loops but do not have any iterator:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<string> vectA;
vector<int>::iterator it;

string name[]={"John", "Betty", "Ram"};

for (int i=0; i<3; i++)
{
vectA.push_back(name[i]);
cout << vectA[i] << " ";
}

vectA.insert(vectA.begin(), "Ron");
vectA.push_back("Bob");

cout << "\n\nAfter......\n\n";
for (int i=0; i<5; i++)
{
cout << vectA[i] << " ";
}
cout << "\n\n";

}


u know how to edit mine with this:
(it=vectA.begin(); it!=vectA.end(); it++)

once again, sorry for troubling u...
Last edited on
1
2
for( int i=0; i<vectA.size(); i++)
    //do something with vectA[i] 
Is the same as
1
2
(it=vectA.begin(); it!=vectA.end(); it++)
    //do something with *vectA 
Last edited on
hmm.. ok tks a lot. sorry for ur time
Topic archived. No new replies allowed.