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;
}
#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".