You cannot declare:
string a[n]; //declaring an array of type string
Why?
ISO C++ forbids variable length array ‘a’
Instead, you should use a vector of string and .push_back() each new string you add, e.g.
#include <iostream> #include <string> #include <vector> int main (void) { int n = 0; std::cout << "enter the number of strings: "; std::cin >> n; if (n < 1) { std::cerr << "error: invalid number of strings.\n"; return 1; } std::vector <std::string> a; // vector of strings for (int i = 0; i < n; i++) { /* read each string */ std::string tmp; std::cin >> tmp; /* into a temp string */ if (!std::cin.eof() && !std::cin.fail()) /* validate read */ a.push_back(tmp); /* add string to vector */ /* output string and first character using indexes */ std::cout << "string[" << i << "]: " << a[i] << " (a[" << i << "][0]: " << a[i][0] << ")\n"; } }
Example Use/Output
$ ./bin/stringindex enter the number of strings: 4 My string[0]: My (a[0][0]: M) Dog string[1]: Dog (a[1][0]: D) Has string[2]: Has (a[2][0]: H) Fleas! string[3]: Fleas! (a[3][0]: F)
Look things over and let me know if you have any questions.