Reputation:
I was just curious to know how to create an array of strings. I am looking to make an array of 10 strings and each string can have 20 characters.
#include <iostream>
int main()
{
char a[10] , str[20];
for (int x = 0 ; x<10 ; x++)
{
for (int y = 0 ;y<20; y++ )
{
cout<<"String:";
cin>>str[y];
a[x]=str[y];
}
}
for (int j = 0 ; j<10 ; j++)
cout<<a[j]<<endl;
return 0;
}
Newbie in C++ with an open mind :)
Upvotes: 0
Views: 193
Reputation: 66371
In order of preference:
A vector of 10 strings:
std::vector<std::string> aVector(10);
An array of 10 strings:
std::string anArray[10];
If you really want to use zero-terminated C strings:
typedef char MyString[21]; // 20 + 1, for the terminating zero
MyString arrayOfThem[10];
or, the more cryptic variant
char anArray[10][21];
Upvotes: 0
Reputation: 389
What are you doing is more C approach.
Anyway:
char strings[10][20];
//Accessing each string
for(int i = 0; i < 10; i++)
{
//Accessing each character
for(int j = 0; j < 20; j++)
{
char character = strings[i][j];
}
}
In c++ you would rather use:
std::string strings[10];
Or the best option is:
std::vector<std::string> strings(10);
in c++ 11 you can iterate over last case like this:
for(auto singleString : strings)
{
}
Upvotes: 0
Reputation: 117856
How about instead you use a
std::vector<std::string> my_strings(10); // vector of 10 strings
You will have a much easier time this way than statically-size char
arrays.
You then get all the features of the std::vector
container, including dynamic size.
You also get all the nice features of the std::string
class.
Upvotes: 4