Help-copying output to txt


Hello,

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
 
int main () {
   
	char str1 [10] = "Hello, ";
	char str2 [10] = "World";
	
   // open a file in write mode.
   ofstream outfile;
   outfile.open("csc331_prog1.txt");

   	strcat ( str1 , str2 );
    cout << str1 ; 
        
    // close the opened file.
   outfile.close();
   
    // open a file in read mode.
   ifstream infile; 
   infile.open("csc331_prog1.txt"); 
  
	cout << str1 ;

   // close the opened file.
   infile.close();

  
   return 0;
}
You don't need the things after line 19. Just remove them.
Instead add

outfile << str1 ;

after line 16.
Hi,

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.
thank you @coder777 & @treefitty
And realize that the following is invoking undefined behavior:

1
2
3
4
5
6
7
   
	char str1 [10] = "Hello, ";
	char str2 [10] = "World";
	
...

   	strcat ( str1 , str2 );
'
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.
Last edited on
Topic archived. No new replies allowed.