| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
The output I need is
AA*aa*BB*bb*CC*cc*DD*dd* #include <iostream> #include <cstring> using namespace std; int main() { char s1[]="AA BB CC DD"; char s2[]="aa bb cc dd"; char *token1Ptr; char *token2Ptr; //cout << "Enter first sentence : " ; //cin >> s1; //cout << "\n\nEnter second sentence : "; //cin >> s2 ; token1Ptr = strtok ( s1 , " "); token2Ptr = strtok ( s2 , " "); while (token1Ptr != NULL && token2Ptr != NULL ) { cout <<token1Ptr << "*"<< token2Ptr << "*"; token2Ptr = strtok ( NULL , " "); token1Ptr = strtok ( NULL , " "); } cout<< endl<<endl; return 0; } |
|
#2
|
||||
|
||||
|
What gets output when you run this script as you have it?
|
|
#3
|
|||
|
|||
|
my output is
AA*aa*bb*cc* |
|
#4
|
|||
|
|||
|
You cannot use the strtok function the way you are. The strtok function uses a static var for parsing the string into tokens. If multiple, or simultaneous calls, are made there is a good chance you will get inaccurate results. So you cannot use this function simultaneously on different strings.
Code:
char s1[]="AA BB CC DD\0";
char s2[]="aa bb cc dd\0";
char *ptr1 = s1;
char *ptr2 = s2;
char *output = new char[256];
int index1=-1;
int index2=-1;
memset(output, '\0', 256);
index1 = strcspn(ptr1, " ");
index2 = strcspn(ptr2, " ");
while(index1 > 0 && index2 > 0)
{
strncat(output, ptr1, index1);
strcat(output, "*");
ptr1 += index1 + 1;
strncat(output, ptr2, index2);
strcat(output, "*");
ptr2 += index2 + 1;
index1 = strcspn(ptr1, " ");
index2 = strcspn(ptr2, " ");
}
cout<<output<<endl<<endl;
delete[] output;
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Mixing strings !! |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|