class constructor error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>	//Include input output stream
#include <cstring>	//Include C type string
#include <cstdlib>	//Include for use of atoi
using namespace std; 	//Define namespace
class A{					//Class definition
public:						//Public Domain
A(char * s){					//Constructor taking string array
	cout << "\nArgument given = " << s;	//Print value s points to
	char * p = strtok(s,", ");		//Get first token of ',' and place in p pointer
	if(p){					//If p is not NULL	
	int i = atoi(p);			//Return the integer value p points to
	cout << "\nInteger made = " << i;	//Print integer
	}
}
~A(){}						//Distructor
};
int main(){				//Main starts
	char s[80] = "123,123";		//Char array size 80, initialized "123,123"	
	A a1(s);			//Create a1	<-----------------------WORKS
	A a2("123,123");		//Create a2 <-----------------------ERROR	
	return 0;			//End successfully
}


While compiling this warning occurs

/**Compiler WARNING : deprecated conversion from string constant to 'char*'**/

In second case here the program crashes

char * p = strtok(s,", ");
Last edited on
strtok doesn't like it when a constant string is passed to it, as it likes to be able to modify the original string.

This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.


-Albatross
@Albatross
Thank you
1
2
3
char as[80];			//char array to store value s points to
strcpy(as,s);			//copy content of s to as
char * p = strtok(as,", ");	//Get first token of ',' and place in p pointer 

This solved the crash problem and now works.
Need a bit of help with the compiler warning, any tip to do it better, any way to make a constructor for this situation?
Last edited on
Change all your char * to const char *
tried that but it does not solve the problem
strtok doesn't like it when a constant string is passed to it, as it likes to be able to modify the original string.
This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.
-Albatross
Topic archived. No new replies allowed.