Fixing the program

closed account (1Cj3ko23)
Rewrite the following program correcting any mistakes and adding missing code so that it reads a value from the file "input.txt" and writes it to the file "results.txt"

1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>

int main()
{
	int n;
	ifstream inData;
	
	outData.open("results.txt)
	cin >> n;
	outData << n << endl;
	return 0;
} 
Last edited on
Sounds like that is your homework. What errors do you see in it?
Last edited on
closed account (1Cj3ko23)
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bits/stdc++.h>
using namespace std;

int main()
{
	int n;
	ifstream \"input.txt\";
	
	outData.open(\"results.txt\");
	cin >> n;
	outData << n << endl;
	return 0;
} 


@keskiverto
This is what I thought it was but it was wrong. I just wanna know how to do it so next time it shows up on my test I can do it correctly.
Last edited on
So when you compiled your most recent version, and it came up with these errors, was that not any help to you?

Test.cpp:7:11: error: stray ‘\’ in program
    7 |  ifstream \"input.txt\";
      |           ^
Test.cpp:7:12: warning: missing terminating " character
    7 |  ifstream \"input.txt\";
      |            ^
Test.cpp:7:12: error: missing terminating " character
    7 |  ifstream \"input.txt\";
      |            ^~~~~~~~~~~~~
Test.cpp:9:15: error: stray ‘\’ in program
    9 |  outData.open(\"results.txt\");
      |               ^
Test.cpp:9:16: warning: missing terminating " character
    9 |  outData.open(\"results.txt\");
      |                ^
Test.cpp:9:16: error: missing terminating " character
    9 |  outData.open(\"results.txt\");
      |                ^~~~~~~~~~~~~~~~
Test.cpp: In function ‘int main()’:
Test.cpp:9:9: error: expected initializer before ‘.’ token
    9 |  outData.open(\"results.txt\");
      |         ^
Test.cpp:11:2: error: ‘outData’ was not declared in this scope
   11 |  outData << n << endl;
      |  ^~~~~~~
closed account (1Cj3ko23)
I honestly have no clue what I am doing with this code.
it reads a value from the file "input.txt"
1
2
outData.open("results.txt)
cin >> n; 

Where does the code read from?
Where should it read from ?
Without error messages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>

int main()
{
	std::ifstream inData("input.txt");

	if (inData) {
		std::ofstream outData("results.txt");

		if (outData) {
			int n {};

			if (inData >> n)
				outData << n << '\n';
		}
	}
}


how to do it so next time it shows up on my test I can do it correctly


The issue is not that you will be able to do the same the next time you get asked, it's that you understand the principles as to how it's done so that you know/understand how to open files for reading/writing, how to read/write data to files and how to check if a file operation has completed ok. Once you understand this, then you'll be able to correctly do any file based question.

Last edited on
Topic archived. No new replies allowed.