Reputation: 27
I want to have 2 strings as input so I can use getline(cin,s)
(so I can pick the whole line until '\n'
) and then I want to search the second array if it contains the word of the first array without using string::find()
or strstr()
.
But I still can't find a way to either convert strings to arrays
int main()
{
string s;
string s2;
char array[50];
char array2[50];
cout<<"Give me the first word"<<endl;
getline(cin,s);
cout<<"Give me the text"<<endl;
getline(cin.s2);
array=s;
array2=s2;
}
The second way I was thinking was doing the job from the start with arrays:
char array[50];
cin.getline(array,50);
But if I use straight arrays is there any way I can find the length of the array like we do on strings?
//example
string s;
int x;
getline(cin,s);
x=line.length();
Upvotes: 3
Views: 67872
Reputation: 29976
Just don't do it, because you don't need to do it.
You could use the c_str()
function to convert the std::string
to a char array, but in your case it's just unnecessary. For the case of finding elements (which I believe is what you need) you can use the string's operator[]
and treat it as if it was an ordinary array.
Upvotes: 4
Reputation: 726987
You can use c_str
member of the std::string
and strcpy
function to copy the data into the arrays:
//array=s;
strcpy(array, s.c_str());
//array2=s2;
strcpy(array2, s2.c_str());
However, you don't have to do that unless you must pass non-constant char
arrays around, because std::string
s look and feel much like character arrays, except they are much more flexible. Unlike character arrays, strings will grow to the right size as needed, provide methods for safe searching and manipulation, and so on.
Upvotes: 3