How does the following print?:
#include <iostream.h>
#include <string.h>
void main()
{
char s[50];
strcpy (s, "What ");
strcat (s, "does this " );
strcat (s, "do?");
cout << s << endl;
}
Can you explain?
How does the following print?:
#include <iostream.h>
#include <string.h>
void main()
{
char s[50];
strcpy (s, "What ");
strcat (s, "does this " );
strcat (s, "do?");
cout << s << endl;
}
Can you explain?
Short answer: the three string operations produce the single output
What does this do?
As showed, the code builds that sentence by copying the first literal into a buffer and then appending two more literals. correctly pointed out modern compilers will complain about old headers/usage, and was right to flag the header choice.
How it works (quick, concrete facts)
strcpy copies bytes from the source into the destination including the terminating NUL byte. strcat scans the destination to the terminating NUL, then copies the characters from the source and writes a final NUL. See strcpy and strcat.strcat calls also re-scan the already-built string each time, which is wasteful for many concatenations.Safer, practical advice
std::string for concatenation: it manages memory, is readable, and avoids many common errors (std::string).-fsanitize=address,undefined) or valgrind to catch overruns.main signature and up-to-date headers; see the standard rules for main (main function rules).These points expand on the replies already in the thread and focus on the real risks (undefined behavior and inefficiency) and practical, modern fixes.
Jump to Post— jwenting 1,905All it prints is a compiler error and some warnings when compiled using GCC.
Correct code is:
#include <iostream> #include <string> using namespace std; int main() { char s[50]; strcpy (s, "What "); strcat (s, "does this " ); strcat (s, "do?"); cout << s << …
All it prints is a compiler error and some warnings when compiled using GCC.
Correct code is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char s[50];
strcpy (s, "What ");
strcat (s, "does this " );
strcat (s, "do?");
cout << s << endl;
return 0;
} which prints exactly what you'd expect it would...
The C-style string handling functions are declared in <cstring>, not <string>.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.