fstring not reading from .txt file - c++

I am trying to write a program that will read a .txt file that is called when the program is run from terminal.
the command used will be;
$ ./myexecutable input.txt
My program and the input.txt are in the same directory. My code so far is as follows
#include <string>
#include <fstream>
using namespace std;
int main(int argc , char* argv[]){
string temp = "here";
string filename = argv[1];
ifstream myFile (filename);
myFile.open(filename);
if (myFile.is_open()){
while (getline (myFile, temp)){
cout << temp << endl;
myFile.close();
}
} else {
cout <<< "You have Entered Wrong File Name" << endl;
}
cout << "do with the simple program" << endl;
return 1;
};
but the output I get is just
file opened, do with the simple program
I am not really familiar with fstream so don't know where I may have gone wrong. I followed their tutorial found here.
but clearly I've done something wrong.
Thanks for your help.

This is the corrected code!!
You were opening myFile twice!!
First time in this statement ifstream myFile (filename);
Second time in this statement-myFile.open(filename);
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc , char* argv[]){
string temp = "here";
string filename = argv[1];
ifstream myFile (filename);
if (myFile.is_open()){
while (getline (myFile, temp)){
cout << temp << endl;
myFile.close();
}
} else {
cout << "You have Entered Wrong File Name" << endl;
}
cout << "do with the simple program" << endl;
return 1;
};

Related

File won't open, I don't know why

My FILE WONT OPEN HELP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input_file_name, output_file_name; //file names
ifstream infile; //input file object
ofstream outfile; //output file object
//prompt user for input file
cout << "Enter the input file name: ";
cin >> input_file_name;
//open input file
infile.open(input_file_name.c_str());
//check if file opened successfully
if (!infile)
{
cout << "Error: Unable to open file" << endl;
cout << "Terminating program...";
return 1;
}
else
{
cout << "Successfully opened file!";
}
return 0;
}
when asked for user input i type filename.txt and it wont display successfuly opened message? why....i have the filename.txt on my pc
First off, pardon my use of 'goto', I just felt like it... Try something like what I have shown below where I check if the file actually opened (save the code stub as "asdf.cpp"). Of course you will have to read the data into an array, but it may be a good place to start.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
string line;
ifstream f("asdf.cpp");
if ( !f.is_open() )
goto error_file_not_open;
while( getline(f, line) )
cout << line << endl;
f.close();
return 0;
error_file_not_open:
cout << "Could not open file" << endl;
return -1;
}
If you want to save and read values from/to file, then try something like this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
// Write values to a file
const int size = 5;
int values[] = { 1,2,3,4,5,6 };
ofstream myfile("lol.txt");
if (myfile.is_open())
{
for (int count = 0; count < size; count++) {
myfile << values[count] << endl;
}
myfile.close();
}
else {
cout << "Unable to open file";
}
// Write read values from a file
std::ifstream file("lol.txt");
if (file.is_open()) {
std::string line;
while (getline(file, line)) {
cout << line.c_str() << endl;
}
file.close();
}
else {
cout << "Unable to open file";
}
}
I'am afraid that your file is not an ANSI-ASCII encoded text file. May be it is encoded by UTF-8 or the Unicode format. The following code will check that the encode of your file. Just try to run it or you could open the lol.txt by any text editor such as, vscode or notepad++.
It will show the encode format of the file at the right-down corner.
Another way to prevent from this issue is try to save the text file to the ANSC-ASCII format. Hope this will help! ^_^
#include <iostream>
#include <fstream>
using namespace std;
unsigned char UTF8Header[] = {0xef, 0xbb, 0xbf};
unsigned char UNICODEHeader[] = {0xff, 0xfe};
int main()
{
char fileName[] = "lol.txt"; // replace the file with your actual file name.
std::ifstream in;
char buffer[3] = {0};
in.open(fileName, std::ios::in | std::ios::binary);
if (!in.is_open())
{
std::cout << "Error opening file";
return -1;
}
if (!in.eof())
in.read(buffer, 2);
if (!in.eof())
in.read(buffer + 2, 1);
if (buffer[0] == UNICODEHeader[0] && buffer[1] == UNICODEHeader[1])
cout << "The file is encoded by unicode format" << endl;
else if (buffer[0] == UTF8Header[0] && buffer[1] == UTF8Header[1] && buffer[2] == UTF8Header[2])
cout << "The file is encoded by UTF-8 format" << endl;
return 0;
}

Read and replacing text from a text file, C++

I don't want to change the text inside the file, just the output.
The text in the file reads "C++ is difficult and programming is difficult"
What I want the program to do is to read that, but replace the word "difficult" with the word "easy", so that it reads as "C++ is easy and programming is easy" actually touching or replacing anything in the text file.
This is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile("difficult.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
This would be as simple as:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string line;
ifstream myfile("difficult.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
if(line == "difficult") cout << "easy" << '\n';
else cout << line << '\n';
// OR
if(line == "difficult") line = "easy";
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

Line and word counter function not adding up correctly C++

This program is supposed to tell the user how many words and lines are in their program (text file only). The two functions that I have written both work, except the num_of_lines function is counting one more line than is correct every time and the num_of_words function is off by about 300 words every time. Not sure what I am doing wrong here. Any help will be greatly appreciated, thanks. I copy and pasted an output after my code and compared it to wc.
#include <iostream>
#include <fstream>
#include <cctype>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_words(string name)
{
int cnt2 = 0;
ifstream iwords;
iwords.open(name);
string w;
if(iwords.is_open())
{
while(iwords >> w)
{
cnt2++;
}
}
else cerr <<"can not open" + name << endl;
iwords.close();
return(cnt2);
}
int num_of_lines(string name)
{
int cnt3 = 0;
string line;
ifstream ilines;
ilines.open(name);
if(ilines.is_open())
{
while(getline(ilines, line))
{
cnt3++;
}
}
else cerr <<"can not open" + name << endl;
ilines.close();
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(string name);
if(argc == 1)die("usage: mywc your_file");
string file;
file = argv[1];
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int b;
b = num_of_words(file);
cout <<"Words: " << b << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Zacharys-MBP:c++ Zstow$ my sample.txt
Chars: 59526
Words: 1689
Lines: 762
Zacharys-MBP:c++ Zstow$ wc sample.txt
761 2720 59526 sample.txt
Zacharys-MBP:c++ Zstow$
Most files (especially programs) will end in a new line. You may not see this in your editor but it is probably there. You will have to check the last line to see if it actually contains any content, or if it is empty.
The istream operator (>>) will detect any group of characters between whitespace to be a "word." So if you're parsing programs, you may have:
for(int i=1; i<73; i++)
The istream operator will see 4 words: [for(int, i=1;, i<73;, i++)]

C++ How do i add a string to an existing text file without overwriting it?

I have coded a programm which can load one text file, can decide how long each word is and can write txt files based on the length of the words. But when i run the programm, the new text files are always filled with just one word(each new word with an already existing text file for his length just overrides the text file)
The start text file looks like this():
http://i.stack.imgur.com/WBaRf.png
My new created text files(named after their length for example: 7.txt) after i runned the programm:
http://i.stack.imgur.com/6QKgE.png
My code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
char filename[128];
ifstream file;
char line[100];
cout << "Input filename: " << flush;
cin.getline(filename, 127);
file.open(filename, ios::in);
if (file.good())
{
file.seekg(0L, ios::beg);
int number = 0;
while (!file.eof())
{
file.getline(line, 100);
stringstream stream;
stream << line;
number++;
cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
std::stringstream sstm;
int laenge = stream.str().length();
string txt = ".txt";
sstm << laenge << txt;
string result = sstm.str();
std::ofstream outFile(result);
outFile << line << endl;
outFile.close();
}
}
else
{
cout << "File not found" << endl;
}
while (true)
{
};
return 0;
}
My goal is that i have sorted the whole words into the file their files, the only problem is that they overwrite themself... How can i get rid off that?
If you don't want to overwrite the content of the file, you can open the file and specify that you want to append to the file:
std::ofstream outFile(result, ios::app);
// ^^^^^^^^

Cout doesn't print on display (console)

so i have a code that's supposed to find a string of characters in a certain .txt file, if the input is in the file, it says "yey i found it" but when it isnt, its supposed to say "didnt find anything", but it just skips that step and ends.
I'm a beginner so sorry for any obvious mistakes.
#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
cin.get();
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}
There are three possible cases.
The file was not successfully opened.
The file was successfully opened, but the string was not found.
The file was successfully opened, and the string was found.
You have a printout for cases 1 and 3, but not 2.
By the way, your loop condition is wrong. Use the result of the call to getline, which is the ostream object itself after the read attempt.
while (getline(MyFile, line))
{
...
}
The loop will terminate upon an unsuccessful read attempt, which will happen after you read the last line. The way you have it, you will try to read after the last line, which will be unsuccessful, but you will still try to process that non-existent line because you don't check eof until the loop starts over.
Just comment out //cin.get(); , you dont need it.
Output:
Welcome, insert the string to find in the file.
apple
Found it ! your input was : apple
Other than that, it works like a charm.
Corrected code:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
setlocale(LC_ALL, "");
string hledat;
int offset;
string line;
ifstream Myfile;
cout.flush();
cout << "Welcome, insert the string to find in the file. \n \n \n" << endl;
//cin.get(); <----- corrected code
cout.flush();
Myfile.open("db.txt");
cin >> hledat;
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line);
if ((offset = line.find(hledat, 0)) != string::npos)
{
cout.flush();
cout << "Found it ! your input was : " << hledat << endl;
}
}
Myfile.close();
}
else
{
cout.flush();
cout << "Sorry, couldnt find anything. Your input was " << hledat << endl;
}
getchar();
system("PAUSE");
return 0;
}