c++ - Error in String class to CString Conversion -
i want put 3 string variables in 1 array besides each other cstring. code gives me error declaration.
#include <iostream> #include <string> using namespace std; int main() { string str1, str2, str3; cin >> str1 >> str2 >> str3; int length_str1 = str1.size(), length_str2 = str2.size(), length_str3 = str3.size(); char acstring[length_str1+length_str2+length_str3+1]; string str_array [] = {str1, str2, str3}; strcpy(acstring, str_array.c_str()); return 0; }
errors:
there 2 errors in code:
1. 14:32: error: request member 'c_str' in 'str_array', of non-class type 'std::string [3] {aka std::basic_string<char> [3]}' 2. 14:39: error: 'strcpy' not declared in scope
reasons:
- first error because trying call
c_str
str_array
pointer array of strings, right way call string i.e.str_array[someindexofarray]
- reason behind second error
string.h
contains methodstrcpy
not included in program.
solution:
try following code:
#include <iostream> #include <string> #include <string.h> //for strcpy , strcat method using namespace std; int main() { string str1, str2, str3; cin >> str1 >> str2 >> str3; int length_str1 = str1.size(); int length_str2 = str2.size(); int length_str3 = str3.size(); char acstring[length_str1+length_str2+length_str3+1]; string str_array[] = {str1, str2, str3}; strcpy(acstring, str_array[0].c_str()); //copy first index of array for(int =1;i<3;i++) //concatenate each index of array strcat(acstring, str_array[i].c_str()); return 0; }
hope helps.
Comments
Post a Comment