I am trying to create a program that will run in the console with "Hello World" and then copy that output into a text. Could you please tell me how to fix my code. Thank you
Also, my current output display "hello world" twice
cout is specifically for outputting to console (Cout = Console Out). When writing to your file, you want "outfile << str1;"
Two more things you can do, add "<< endl;" after all cout calls to add a blank return in the output, and check for "is_open()" after calling open() on file IO. Generally you want to do something like
1 2 3 4 5 6 7 8 9 10 11 12 13
ifstream infile;
infile.open("file.txt");
if(infile.is_open())
{
// do things
infile.close();
}
else
{
// couldn't open file, probably quit or log an error
cout << "Can't find file" << endl;
return 1;
}
Line 15: You're going to overrun str1. str1 is 7 characters. str2 is 5 characters. The result of the strcat operation will be 13 characters 7 + 5 + 1 for null terminator, however, you have only reserverd 10 characters for str1.
'
You are overflowing the destination array. Remember the destination must be large enough to hold the contents of the combined string including the mandentory end of string character.
You really should be using C++ strings or in this case just write both strings to the output one after the other: cout << str1 << str2 << '\n';
if you must use a char array on a fixed value, use [] with no size at all:
char st[] = "whatever";
if you need to modify, and possibly make bigger, the string, just use a huge value:
char st[200] = "whatever";
strcat(st, "a whole bunch more text and stuff"); // etc this would fail on the [] example but not the [200] version
but all this guess the size game stuff goes away with C++ strings, which manage the problems for you behind the scene.