Reputation: 445
As a homework, I have to make a program which replaces all the words made of 3 letters with a "*".
For example:
input: cod is everything and I love it
output: * is everything * I love it
Here is my program:
int main()
{
char cuvant[101], final[101];
char* pch;
cin.get(cuvant, 100);
pch = strtok(cuvant, " ");
while (pch != NULL)
{
if (strlen(pch) == 3)
{
strcat(final, " *");
}
else
{
strcat(final, " ");
strcat(final, pch);
}
pch = strtok(NULL, " ");
}
cout << final;
}
I don't get any error - but the output is blank. Also, the program doesn't exit with the code 0 (as it should be), it says "exited with code -1073741819". So obviously something is going on.
Am I using strtok/strcat wrong?
I feel like strcat can't be used in my case and this is the reason for the error, but I'm not sure. Am I right?
If so, how can I solve my problem?
Thanks.
Upvotes: 0
Views: 498
Reputation: 475
you can make the if statement looks like this :
if (strlen(pch) == 3)
{
strcat(final, "* ");
}
else
{
strcat(final, pch);
strcat(final, " ");
}
so the final string will not start by termination char.
Upvotes: 1
Reputation: 76305
C++'s string extractors split input on whitespace; that can save you a bunch of parsing.
std::string word;
std::string result;
while (std::cin >> word) {
result += ' ';
if (word.length == 3)
result += '*';
else
result += word;
Upvotes: 1
Reputation: 115
try this for 'c'
memset( cuvant, 0, sizeof( cuvant ));
memset( final, 0, sizeof( final ));
Upvotes: 1
Reputation: 4366
You need to initialize final
strcpy(final, "");
to make it null terminated before you start using it with strcat.
or just set
final[0] = 0;
Upvotes: 2
Reputation: 264421
Your problem is that all the C-String
functions expect your string to be null terminated (ie the character '\0'
as the last character of a string.
The problem is that final
is not initialized. It can contain any amount of raw garbage. So when you use strcat()
it has to find the end (which could be anywhere).
The solution is to initialize final
to make sure it is a zero length C-String
.
char cuvant[101];
char final[101] ={0}; // Fills the array with zero
Or.
char final[101];
final[0] = '\0'; // Make a C-String of length 0
Return code.
In C++ the return code is 0. But in C it is undefined (as you have no return statement). So you compiled your code with the C compiler not the C++ compiler.
An undefined value can be anything. The value -1073741819
is valid as anything.
Upvotes: 3