undefined behavior output in deque

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include<iostream>
#include<deque>
using namespace std;
deque<string> q;

void trans(string x){
    if(x.length()>0){
    if(x[0]=='['){
        int i =1;
        while(x[i]!='[' && x[i]!= ']' && i<x.length())i++;
        q.push_front(x.substr(1,i-1));
        trans(x.substr(i)+"");
        return;
    }else if(x[0]==']'){
    	int i =1;
        while(x[i]!='[' && x[i]!= ']' && i<x.length())i++;
        q.push_back(x.substr(1,i-1));
        trans(x.substr(i));
        return;
    }else{
	char h[]={x[0]};
	string hh(h);
	q.push_back(hh);
	trans(x.substr(1));
	return;
    }
}
}

int main(){
string xs;
cin>>xs;
trans(xs);
deque<string>::iterator it = q.begin();
while(it!= q.end())
cout<<*it++;
	
}


this is the input
 
This_is_a_[Beiju]_text



outputs
 
BeijuTи�&�hP��&�iз�&�sP��&�_ж�&�iP��&�sе�&�_P��&�aд�&�_P��&�_text


it should output
BeijuThis_is_a__text


here is the link of the compilation
https://ideone.com/2FSqQg


i think the errors occur in the second recursive call for the trans function but i dont know where exactly .. is it when i pass the variable or is it something i should be doing the deque ?
Last edited on
Why do you need recursion? Isn't it simply a case of looking for the sequence [ ... ] and moving it?
When passing a const char* (or a char array) to the string constructor it assumes it points to the first element in a null-terminated array.

The array that you create on line 21 is not null-terminated, i.e. it does not end with a null-character '\0' (zero byte). When this array is passed to the string constructor on line 22 it will loop though and copy the chars in memory until it finds a null-character. This is probably why you get all that garbage in your string.

If you want to construct a string from a char array that is not null-terminated you will need to explicitly pass the length as the second argument.

1
2
char h[]={x[0]};
string hh(h, 1);

In this case it seems a bit unnecessary to construct a char array. You can pass a char directly to the string constructor but then you also need to pass an argument to decide how many times the char should be repeated.

 
string hh(1, x[0]);

You can also initialize the string using { } (similar to how you initialize an array). This is probably the simplest solution but it only works on modern compilers with support for C++11 or later.

 
string hh{x[0]};
Last edited on
Kbw
 
Why do you need recursion? Isn't it simply a case of looking for the sequence [ ... ] and moving it? 


nope whenever [ is met you should transfere what's after in the beginning and when ] is met u should transfere what is after in the end

it's not necessary to have [ then ] it could just be ] in the middle
Last edited on
thanx a lot Peter <3
Topic archived. No new replies allowed.