Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an array of strings in C++?

Tags:

c++

arrays

I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?

Possible non-solutions:

vector<string> v; v.push_back("abc"); b.push_back("xyz");  for(int i = 0; i < v.size(); i++)     cout << v[i] << endl; 

Problems - no way to create the vector on one line with a list of strings

Possible non-solution 2:

string list[] = {"abc", "xyz"}; 

Problems - no way to get the number of strings automatically (that I know of).

There must be an easy way of doing this.

like image 832
naumcho Avatar asked Aug 29 '08 18:08

naumcho


People also ask

How do you declare a string array?

A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array.

Can I put string in array in C?

First Case, take input values as scanf("%s", input[0]); , similarly for input[1] and input[2] . Remember you can store a string of max size 10 (including '\0' character) in each input[i] . In second case, get input the same way as above, but allocate memory to each pointer input[i] using malloc before.

How do you input an array of strings?

Since you know that you want to have an array of 20 string: String[] array = new String[20]; Then your for loop should use the length of the array to determine when the loop should stop. Also you loop is missing an incrementer.

How do you declare a string in C?

Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.


1 Answers

C++ 11 added initialization lists to allow the following syntax:

std::vector<std::string> v = {"Hello", "World"}; 

Support for this C++ 11 feature was added in at least GCC 4.4 and only in Visual Studio 2013.

like image 159
Anthony Cramp Avatar answered Oct 06 '22 11:10

Anthony Cramp