strcmp works sometime, but not always & blocks output to screen
This code is supposed to put 3 words in alphabetical order. It works fine for 5 of 6 possibilities. However, when I enter something like "rat cat dog" it doesn't (skips "rat" in Code::Blocks, no output in repl.it). Also, no cout's in the if/else structure print at all. Any ideas?
Code:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
char word1[20];
char word2[20];
char word3[20];
char phrase[64];
cout << "Enter three words, pressing Enter after each.\n";
gets(word1);
gets(word2);
gets(word3);
char first[20];
char second[20];
char third[20];
if (strcmp(word1, word2) > 0 && strcmp(word1, word3) > 0)
{
strcpy(third, word1);
if (strcmp(word2, word3) > 0)
{
strcpy(second, word2);
strcpy(first, word3);
}
else
{
strcpy(second, word3);
strcpy(second, word2);
}
}
else if (strcmp(word2, word1) > 0 && strcmp(word2, word3) > 0)
{
strcpy(third, word2);
if (strcmp(word1, word3) > 0)
{
strcpy(second, word1);
strcpy(first, word3);
}
else
{
strcpy(second, word3);
strcpy(first, word1);
}
}
else
{
strcpy(third, word3);
if (strcmp(word1, word2) > 0)
{
strcpy(second, word1);
strcpy(first, word2);
}
else
{
strcpy(second, word2);
strcpy(first, word1);
}
}
cout << "In order...\n";
cout << first << endl
<< second << endl
<< third << endl << endl; // puts
return 0;
}
Re: strcmp works sometime, but not always & blocks output to screen
Please, use CODE tags while posting code snippets!
Use this # toolbar button to achieve it:
Attachment 36021
Re: strcmp works sometime, but not always & blocks output to screen
gets() has been removed from the standard. use gets_s() instead. As this is C++, why not use std::string?
You have a 'typo':
Code:
strcpy(second, word3);
strcpy(second, word2);
Can you spot it?
Code:
strcpy(second, word3);
strcpy(first, word2);
The reason you're currently getting different output on different systems in that in the failure case, first doesn't have anything copied into it and hasn't been initialised. Hence cout << first will display whatever happens to be in memory at the location pointed to by first. Variables should always be initialised:
Code:
char word1[20] {};
char word2[20] {};
char word3[20] {};
char first[20] {};
char second[20] {};
char third[20] {};