Hey folks, I have a program that is meant to read in lines from a text file, and split them into tokens around ", " using strtok(). So for instance, "WSAD, 1234" should be split into "WSAD" and then "1234". However, when I execute my code, I get a runtime error. I have spent quite a while looking at my code, but I still don't understand the problem. Could a kind soul look into it and tell me what I'm doing wrong? My code is below:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
string filename,obj;
cout<<"Please enter filename: ";
cin>>filename;
ifstream file;
file.open(filename.c_str());
if(!file)
{ cout<<"Error in opening file"<<endl;}
else
{
char* copy;
char* un, *deux;
while(getline(file,obj))
{
cout<<obj<<endl;
strcpy(copy, obj.c_str());//error occurs around or after here
un=strtok(copy,", ");
deux=strtok(NULL,", ");
}
strcpy(copy, obj.c_str());//error occurs around or after here
This is an attempt to copy the letters from obj into the memory space pointed at by the pointer copy. Where is the pointer copy pointing?
Well, you created it like this: char* copy;
so it starts out just pointing at some random memory somewhere, that could be anywhere, and that's it.
So you're trying to write over some random piece of memory somewhere that doesn't belong to your program, and the OS spots this and stops the program, as it should.
You have to make that pointer actually point at memory that is yours to write on.
I see. Alright, any suggestions on a suitable way to initialize the pointer? I'm not allowed to use arrays of any kind for any reason, because this is for an assignment and that was a restriction my lecturer implemented.
Since we're coding like it's 1980, we could use malloc.
After reading in the string, you could do something like: char* copy = (char*) malloc(obj.length()); which will definitely be enough space to strtok into.
I'd prefer new: char* copy = newchar[obj.length()]; but that would probably be taken as an array.
Because C++ turned up with new in the eighties, and also brought with it a number of nicer ways to tokenise string objects than using the C function strtok.