A
Alex Vinokur
Here is some program with using strtok() and std::string.
Why does strtok() affect str2 in function func2()?
====== File foo.cpp : BEGIN ======
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
void func1()
{
string str1 ("abcd\nxyz");
string str2 (str1);
cout << "\tBEFORE" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
str1[4] = 0;
cout << endl;
cout << "\tAFTER assignment" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
}
void func2()
{
string str1 ("abcd\nxyz");
string str2 (str1);
cout << "\tBEFORE" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
strtok ((char*)str1.c_str(), "\n");
cout << endl;
cout << "\tAFTER strtok" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
}
int main()
{
func1();
cout << "-------------" << endl;
func2();
return 0;
}
====== File foo.cpp : END ========
====== Run : BEGIN ======
BEFORE
str1 = <abcd
xyz>
str2 = <abcd
xyz>
AFTER assignment
str1 = <abcd xyz>
str2 = <abcd
xyz>
-------------
BEFORE
str1 = <abcd
xyz>
str2 = <abcd
xyz>
AFTER strtok
str1 = <abcd xyz>
str2 = <abcd xyz>
====== Run : END ========
Why does strtok() affect str2 in function func2()?
====== File foo.cpp : BEGIN ======
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
void func1()
{
string str1 ("abcd\nxyz");
string str2 (str1);
cout << "\tBEFORE" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
str1[4] = 0;
cout << endl;
cout << "\tAFTER assignment" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
}
void func2()
{
string str1 ("abcd\nxyz");
string str2 (str1);
cout << "\tBEFORE" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
strtok ((char*)str1.c_str(), "\n");
cout << endl;
cout << "\tAFTER strtok" << endl;
cout << "str1 = <" << str1 << ">" << endl;
cout << "str2 = <" << str2 << ">" << endl;
}
int main()
{
func1();
cout << "-------------" << endl;
func2();
return 0;
}
====== File foo.cpp : END ========
====== Run : BEGIN ======
BEFORE
str1 = <abcd
xyz>
str2 = <abcd
xyz>
AFTER assignment
str1 = <abcd xyz>
str2 = <abcd
xyz>
-------------
BEFORE
str1 = <abcd
xyz>
str2 = <abcd
xyz>
AFTER strtok
str1 = <abcd xyz>
str2 = <abcd xyz>
====== Run : END ========