Hi guys, I am working on C String and I'm having this weird error. here's the code
#include #include #include //#include using namespace std;
//Function Declarations
void get_longest_word (char data[]);
int main()
{
char * MyString;
cout<<"--------------------------------------------------------------"<<endl;
cout<<"\\nTask 1:\\n"<<endl;
ifstream taskonefile("CStringText.txt");
if(! taskonefile.is\_open())
{
cout<<"Cannot Open File!"<<endl;
exit(1);
}
int charCount;
taskonefile.seekg(0, ios::end);
charCount = taskonefile.tellg();
taskonefile.seekg(0, ios::beg);
charCount++;
MyString = new char\[charCount\];
taskonefile.get(MyString,charCount);
cout<<MyString<<endl;
cout<<"\\nTask 2:\\n"<<endl;
cout<<"Longest word in the above paragraph: ";
get\_longest\_word(MyString);
cout<<"\\nTask 3:\\n"<<endl;
int l\_num = 0;
cout<<MyString<<endl;
for(int i =0; i<=strlen(MyString); i++)
{
if (MyString\[i\]=='l' || MyString\[i\]=='L')
{
l\_num++;
}
}
cout << "Number of Ls" << l\_num;
//EXIT+++++++++++++++++++++++++++++++++++++++++++++++++++
cin.get();
return 0;
}
//FUNCTIONS================================================
//TASK 2 FUNCTION
void get_longest_word (char data[])
{
char * token;
char * longest_word = "a";
token = strtok(data, " ,.-");
while (token != NULL)
{
if (strlen (token) >= strlen(longest\_word))
{
longest\_word = token;
}
token=strtok(NULL, " ,.-");
}
cout<<longest\_word<<endl;
}
The problem is when I some to task 3 after calling void get_longest_word the content of MyString which is local to int main() becomes only the first character of the entire string... I have no clue what is happening wrong!
- Stop thinking in terms of limitations and start thinking in terms of possibilities -