0
#include <iostream> #include <string> using namespace std; int main() { int n;cin>>n;//entering number of string to be inputed string a[n];//declaring an array of type string for(int i=0;i<n;i++){ cin>>a[i]; } for(int i=0;i<n;i++){ cout<<a[i]<<endl; } //for manipulating letters of strings cout<<a[0][1]; return 0; } 

To access the elements of a string, we should output the result as a multidimensional array. This seems a bit counter intuitive. Could someone explain is this the right way.

Input 2 asfdsf asfdsafd Output asfdsf asfdsafd s 
1
  • I’m a bit unsure what your question is, since there isn’t an actual question sentence here. What is counter intuitive and what do you need explained exactly? Commented Apr 30, 2018 at 4:46

2 Answers 2

2

A string is an array of characters. So an array of strings is an array of arrays of characters. To access the jth character in the ith string, you use a[i][j].

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think a string is "an array of characters". To be more precise, I think a string is a "sequence" of characters.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.