c++ input/output files

Feb 3, 2020 at 10:45pm
Hey guys, i have got a huge problem with input/output files in c++.. So i can't find program which reads from a file and prints out the largest string in another (out.text) file...I can't even start so please any help, some example will be much appreciated.. I have only this one which reads from a file


1
2
3
4
5
6
7
8
9
10
11
12
int main(){
fstream file;
   string word, t, q, filename;

   filename = "file.txt";

   file.open(filename.c_str());
   while(file >> word)
   {
       cout << word << endl;
return 0; 
}
Feb 3, 2020 at 10:49pm
This will fail to compile because you have a '{' at the start of the while loop which doesn't have a corresponding closing brace '}'.
Feb 4, 2020 at 11:04am
Hello annw3y,

In addition to what TheToaster has said I have found this to be useful.

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
33
#include <iostream>
#include <iomanip>
#include <string>

#include <fstream>

int main()
{
	const std::string inFileName{ "file.txt" };

	int count{};
	std::string word;

	std::ifstream inFile(inFileName);

	if (!inFile)
	{
		std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
		//std::cout<<"\n File \""<<inFileName<<"\" did not open" << std::endl; // <--- An alternative.
		//std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread". Optional as is the header files.
		return 1;  //exit(1);  // If not in "main".
	}

	while (inFile >> word)
	{
		std::cout << word << std::endl;
		count++;
	} // <--- Missing.

	std::cout << "\n There are " << count << " words in the file.\n";

	return 0;
}

In your code how do you know that the input file is open? You should always check the input file. For an output file if the file does not exist it is first created then opened. Not always necessary to check the status of an output file, but a good idea.

You have defined the file stream as an "fstream". This will work until you get to the open statement.

The line file.open(filename.c_str());. If your compiler is set to use the C++11 standards the ".c_str()" is not needed. Also with the stream defined as a "fstream" you need to tell open which mode it will be used in "in", "out" or both.
file.open(filename, std::ios::in); file.open(filename, std::ios::out); or file.open(filename, std::ios::in | std::ios::out);.

It is much easier to use "std::ifstream" and std::ofstream".

The extra code was just for fun.

Andy
Feb 4, 2020 at 11:41am
Hello annw3y,

Your original question and code refer to an input file. It would be a great help is you could post the input file or a good sample.

This could make a difference on how you read the file and process it.

Andy
Topic archived. No new replies allowed.