Argument checking - c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
string STRING;
ifstream infile;
STRING = argv[1];
infile.open(argv[1]);
if (infile.fail())// covers a miss spelling of a fail name
{
cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
return 1;
}
else
{
while(!infile.eof())
{
getline(infile,STRING); // Get the line
cout<<STRING + "\n"; // Prints out File line
}
infile.close();
return 0;
}
}
I have got this program working fine apart from one problem
if the user only runs the program with no file name (what I believe to be called arguments) e.g ./displayfile then I get a Segmentation fault
How would I amend my code so that the program would exit with an error message along the lines of "Add a file name"
My first thought is something along the lines of
if (!argc=2)
{
cout << "ERROR. Enter a file name";
return 1;
}
ADDED:
just in case this matters am compiling using
g++ displayfile.cpp -o displayfile

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[]) {
if(argc != 2) {
cout << "You need to supply one argument to this program.";
return -1;
}
string STRING;
ifstream infile;
STRING = argv[1];
infile.open(argv[1]);
if (infile.fail())// covers a miss spelling of a fail name {
cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
return 1;
}
else {
while(!infile.eof()) {
getline(infile,STRING); // Get the line
cout<<STRING + "\n"; // Prints out File line
}
infile.close();
return 0;
}
}

Besides the obvious check for argc != 2 I couldn't help fixing some of the worse code and the obvious error:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
if (argc != 2)
{
cout << "ERROR. Invalid number of arguments\n";
return 1;
}
ifstream infile(argv[1]);
if (!infile) // covers a miss spelling of a fail name
{
cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
return 1;
}
string STRING;
while(getline(infile, STRING))
cout << STRING << '\n'; // Prints out file line
return 0;
}
You don't need to call ifstream::open, just use the constructor, likewise don't you need to declare STRING so early and neither to initialize it to the file name, since you don't use it. Don't forget, this is not C, you don't need a whole mess of declarations at the beginning of each function.
Second, checking for the flags of a stream is often a bad idea, just check for !infile to find any errors. But the real error is in checking for infile.eof in the while condition, since it only gets set once getline has tryed to read over the end of the file, so you would actually print one (probably empty) line too much. Just check for getline's return value to find any errors or the end of file.
And don't add the newline onto the string when outputting, just put it out after the string. And last but not least, no need for infile.close, since the destructor calls it anyway.

change STRING = argv[1]; to if (argv[1] != null) STRING = argv[1]; not sure though, so you'll have to test it out first.

Related

C++ How to read first user argument using argv[1] and store it in a string to read/write text files

My task is to make a C++ program that will read, write, save, load and append a text file. I have two issues that I've been stuck on so far. The first being, how do you store the first argument entered by a user in a string using argv? Secondly, how do I create the program such that when the user enters in the command the program doesn't exit immediately after, so technically be in a while loop the whole time until prompted by a quit message? I've tried doing this already but my code also goes into a loop.
int main(int argc, char* argv[]) {
while (!inFile.eof()) {
inFile.open("userinput.txt");
getline(cin, line);
if (argc > 1) {
int result = strcmp(argv[1], "load");
if (result == 0) {
cout << "CORRECT" << endl;
}
else{
exit(1);
}
}
}
return 0;
}
Something like this, read program argument, read user input, read/write/append on a file.
#include <iostream>
#include <ios> // new
#include <fstream> // new
using namespace std;
int main(int argc, char* argv[])
{
fstream inFile("userinput.txt", std::ios_base::app | std::ios_base::out); //new, allows to append lines to 'userinput.txt'
while (!inFile.eof()) {
string line;
getline(cin, line);
inFile << line; // new: write the user input on inFile
if (argc > 1) {
int result = strcmp(argv[1], "load");
if (result == 0) {
cout << "CORRECT" << endl;
}
else {
exit(1);
}
}
}
return 0;
}
I don't really know the usage of this though so you should adapt it to your ends.

Count one certain string in a file in C++

This is my code.
I am supposed to count the number of 'duck' in a txt file and print string like "There were 2 ducks in animals01.txt"
Now I get no error and nothing return.
Please tell me what's wrong?
#include <iostream> // for printf()
#include <cstdlib> // for exit(), perror()
#include <fstream> // for ifstream
using namespace std;
int main(int argc, char *argv[])
{
if (argc!=2) {
// if argc is not 2, print an error message and exit
cerr << "Usage: "<< argv[0] << " inputFile" << endl;
exit(1); // defined in cstdlib
}
return 0;
int num = 0;
ifstream ifs;
ifs.open(argv[1]);
string line;
do{
getline(ifs, line);
cout<<line<<endl;
if(line == "duck"){num++;}
}while(!ifs.eof());
cout<<"There were"<<num<<"ducks in"<<argv[1]<< endl;
}
You have the line return 0; before you actually did anything, and when you return main() the program is terminated.
By the way, don't use while(!ifs.eof()) because the eof flag only gets set at the first attempt to read past the end of the file, not when you read exactly to the end of the file due to a line break at the end. Do something like this. Also, fix your indenting as it is very misleading.
Read the file word by word.
Example:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string str, strToSearch = "ducks";
int wordCount = 0;
ifstream fin("thisfile.txt");
while (fin >> str) // Will read up to eof() and stop at every whitespace it hits. (like spaces!)
{
if(str==strToSearch)
wordCount++;
}
fin.close();
cout<<"There were"<<wordCount<<"ducks in thisfile.txt"<<endl;
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++)]

Removing groups of "000" from my file?

In C++ I have made a program that exports to binary and now I am making a reader. It reads correctly, but there is only 1 issue. My file is a file that contains a set of numbers and when it is read and printed to the screen you see, 1470009300047000199. The sets of 3 "000" isn't supposed to be there. I loaded this file using an ifstream and plan to keep it that way. Can someone tell me how to remove the sets of "000" in my file? If I have to write another C++ program that does that I am fine with it, I just need something to remove the "000" and replace it with a space.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Error 1";
return 0;
}
else
{
int FileLength;
ifstream InputFile(argv[1], ios::binary);
ofstream OutputFile("DECOMPILED_FILE.txt");
InputFile.seekg(0, ios::end);
FileLength = InputFile.tellg();
InputFile.seekg(0, ios::beg);
for (int i = 0; i < FileLength; i++)
{
cout << InputFile.get();
}
cin.get();
}
return 0;
}
How about a regular expression ? Try finding the substring '000' on the file, if found, replace it by " ".
Pseudocode:
for each line in the file do:
if line.strstr("000") then
line.replace("000", " ")
cout << line << endl;

Beginning Address Endless Loop

I'm trying to get the beginning address of each line of my file as I read it, and print it out to the screen, but for some reason it just results in an endless loop. The file i'm reading is just a normal text file. Here's what I have going right now.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv){
ifstream file;
string name, lnstr;
int addy;
if (argc > 1)
name = argv[1];
else
{
cout << "Please Enter Your Filename: ";
getline(cin, name);
}
file.open(name.data());
if(!file)
{
perror(name.data());
exit(1);
}
addy = 0;
while(getline(file, lnstr))
{
cout << file.seekg(addy, ios::beg) << endl;
addy++;
}
}
Even if I put 0 as the first parameter of seekg, it still results in an endless loop, or it just shows the same number a bunch of times. Not sure what i'm missing.
When you call ios::beg you set the position of the get pointer to the beginning of the file. You don't actually need this call and this code should work for you:
file.open(name.c_str()); // open file
if(file) {
while(getline(file, lnstr)) {
cout<< lnstr <<endl;
}
}
More on seekg.
I think you want tellg, not seekg.