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.
CodePudding user response:
temp[3]
is null character.
the literal "abc" means the array {'a', 'b', 'c', '\0'}
.
Change
cout<<temp[3]<<endl;
To
cout<<temp[2]<<endl;
CodePudding user response:
you are using temp[3]
but "abc"
means an array of size 4 as follows:
{'a', 'b', 'c', '\0'}
Where '\0'
represents the termination of the string. So temp[3]
is same as '\0'
.
Please use temp[2]
instead to access the last character of the string.