简体   繁体   中英

C++ , Array of strings

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 :)

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.

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)
{

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM