I am trying to extract a single element from a string literal included a list composed of string literals. I used VS Code.
First, I used pointer to make the array of string literals and succeeded in the extracting particular single character in C.
I ran following code to check this:
#include <stdio.h>
int main()
{
char* list[]={"abc","def","ghi"};
printf("%c\n",list[1][1]);
return 0;
}
Then, I tried to use vector instead of array to make the list consists of string literals in C++.
I ran following code but failed:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<const char*> list;
list = {"abc", "def", "ghi"};
for (int i = 0; i < 3; i++){
const char* temp = list[i];
cout<<temp[3]<<endl;
}
return 0;
}
When I ran the code above, just blank was displayed:
I also tried changing const char*
to char*
, but it didn't worked well, too.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<char*> list;
list = {"abc", "def", "ghi"};
for (int i = 0; i < 3; i++){
char* temp = list[i];
cout<<temp[3]<<endl;
}
return 0;
}
I am not sure why my codes does not work well to extract the single character included the element of list
.
Could you please tell me the reason why my didn't work well?
I appreciate if you could help me.
Notations
Based on the comments, I revised my code. I changed char*
to string
as following:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<string> list;
list = {"abc", "def", "ghi"};
for (int i = 0; i < 3; i++){
string temp = list[i];
cout<<temp[3]<<endl;
}
return 0;
}
However, the output is also blank as well.