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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With