C++ convert strings to char arrays

天涯浪子 提交于 2019-12-07 12:02:30

问题


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();

回答1:


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.




回答2:


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::strings 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.



来源:https://stackoverflow.com/questions/13343013/c-convert-strings-to-char-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!