Way to deal with multiple user arguments in C++? - c++

Task Commands Picture Ok, I've progressed a bit more from my previous work but I just can't get past this issue which probably isn't that big. My task, which is basically a text file editor, requires multiple user arguments after the program begins running, ranging from let's say 1 such as "details" to 3 or 4 with random user input like display x y or savepart x y (see attached image). My code currently takes in the first line the user inputs using cin and getline but it can only read known strings such as load userinput.txt (which is the filename), and quit and I don't know how I can store the user's entered values for variables. How do I solve this?
What basically needs to probably change is the getline under the while loop or what's written in the if statements but I've tried everything.
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
string secondword;
string fword;
string line;
ifstream myfile;
fstream fFile;
bool running = true;
int x;
int length;
int main(int argc, char* argv[]) {
while (running) {
getline(cin, fword); //Reads first line user inputs
//if first word equals laod command load file to memory
if (fword == "load userinput.txt") {
ifstream myfile("userinput.txt", ifstream::binary);
myfile.seekg(0, myfile.end); //Searches till end of file
length = myfile.tellg(); //Sets length as total number of chars in file
myfile.seekg(0, myfile.beg); //Searches from the beginning
char* buffer = new char[length]; //Allocates file memory to pointer
cout << "Reading " << length << " characters... " << endl;
myfile.read(buffer,length); //reads file and compares buffer size with legnth size
if (myfile)
cout << "All characters read and stored in memory sucessfully" << endl;
else
cout << "error: only " << myfile.gcount() << " can be read" << endl;;
myfile.close();
}
//Quit
if (fword == "quit") {
running = false; //Breaks while loop statement
cout << "User has quit the program" << endl;
}
//Clear all lines in text
if (fword == "clear all") {
fFile.open("userinput.txt", ios::out | ios::trunc);
fFile.close();
cout << "All lines have been cleared" << endl;
}
//Display All Text
if (fword == "display text") {
myfile.open("userinput.txt", ios::in);
while (getline(myfile, line)) { //read data from file object and put it into string.
cout << line << endl; //print the data of the string
}
}
}
return 0;
}

Related

How would I go about storing words from a plain text file to an array using C++?

I've been tasked with writing a C++ program that opens a text file, determines the length of each word, then produces output stating how many times a particular word length occurs.
I've figured how to open and read the contents of the file.
How would I take each word and store them in an array?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void getFile(string);
void getFile(string filename)
{
string array[2];
short loop = 0;
string line;
ifstream myfile (filename);
if (myfile.is_open())
{
while (!myfile.eof() )
{
getline (myfile,line);
array[loop] = line;
cout << array[loop] << endl;
loop++;
}
myfile.close();
}
else{
cout << "can't open the file";
system("PAUSE");
}
}
int main(){
string fileName;
while (true){
cout << "\nEnter the name of a file: ";
getline(cin, fileName);
if (fileName == ""){
cout << "Invaled file name, enter another!!!"<<endl;
main();
}
else{
getFile(fileName);
}
}
return 0;
}
You do not store words in an array.
You only need to store the word lengths and how often each of them occurred.
If you have a guaranteed and low maximum word length you can even simplify by using an array where the length of the current word is used as an index. Init all entries with 0. Then count entries up when the corresponding word length occurs.

C++ Searching CSV file from inputted string

I am trying to create a program that will load the CSV file and based upon the inputted word search through the file and return any lines that contain the word. The CSV file is a mass download of tweets and has the following columns:
Date & Time Created
The Tweet
The tweets are also surrounded by b'TWEET TEXT HERE' so would need to remove the b' ' from when it printed out. I am unable to change anything to do with the CSV file sadly so cant manually remove it. The issues I am having are:
Listing the total amount of tweets within the file the program just freezes
Removing the b' ' from the tweets
The else statement causes "not found" to be constantly printed
Code I currently have that is returning the tweets that contain the inputted word but also the false positive.
The current output when running the below code
#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string token;
ifstream fin;
fin.open("sampleTweets.csv");
if (fin.is_open())
{
cout << "File opened successfully" << "\n";
}
else {
cout << "Error opening file" << "\n";
}
cout << "Enter search word: ";
cin >> token;
"\n";
string line;
while (getline(fin, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
} else {
cout << token << " not found" << endl;
}
}
fin.close();
char anykey;
cout << "press any key";
cin >> anykey;
return 0;
}
Code I was using for counting total tweets
int count = 0;
char str[140];
while (!fin.eof())
{
fin.getline(str, 140);
count++;
}
cout << "Number of lines in file are " << count;
Any help on this would be amazing as I am quite new to C++ and not sure where to go from here!
You can remove the "b" with erase:
if (line.find(token) != string::npos){
int n= line.find(",");
line.erase(n+1, 3);
cout << line << endl;
}
and you can count the lines inside the while loop:
int count = 0;
while (getline(fin, line)) {
++count;
...
}
EDIT: you can remove the extra quotes and commas like so:
line[n] = ' '; // change comma int space
line.erase(n+1, 4); // remove "b""
line.resize(line.size()-5); // remove trailing """,,

regarding: instance of 'std::bad_alloc'

I read other posts but none of them helping at all,
This code have no error still there is bad_alloc error...
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char super[25];
char name[25],last_name[25];
int length;
char *sym = "#";
char *buffer;
ofstream outfile;
outfile.open("farses.dat",ios::app);
cout << "Writing to the file" << endl;
cout << "Enter your First Name: ";
cin >> name;
outfile << *sym;
outfile << name << endl;
cout << "Enter your Last Name: ";
cin >> last_name;
outfile << *sym;
outfile << last_name << endl;
cout << "Enter The Sentence : ";
cin.getline(super,25);
outfile << super << endl;
outfile.close();
ifstream infile;
infile.open("frases.dat");
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0,ios::beg);
buffer = new char[length];
infile.read(buffer , length);
cout << "\n\nReading from file \n\n" << endl;
cout << buffer << endl;
infile.close();
return 0;
}
This code is terminating after coming to sentence statement..the getline() function is causing problem i guess but when i tried on other two statements(name and last_name),the getline(), it works perfectly..i even degraded the char limit to 5 too but after sentence statement is throw anyways
Thumb rule, don't fool yourself into thinking that your code has no errors. Especially when you clearly got an error. This kind of mindset will make you unable to find errors because everything you see is correct.
You never checked if your streams were open and you entered the wrong file name in the ofstream.
What happens is that, you write your data into a file name farses.dat and then you try to open a file called frases.dat (which I assume is the correct name, it means sentences).
You are getting the cursor position ifstream::tellg of an inexistent file, and it fails so the function returns -1. This is the value of length before you allocate your buffer.
When you do allocate your buffer you get a bad_alloc exception (bad_array_new_length).
Checking if your file was open would, at the very least, have saved you some debug time.
Something like this,
ifstream infile;
infile.open("frases.dat");
if ( infile.is_open() ) {
// File is open, do stuff (...)
if ( length <= 0 ) {
// Empty file / error, don't create buffer!!!
}
// (...)
infile.close();
}
else {
// Couldn't open file
}
EDIT: Fixed error explanation.

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);
// ^^^^^^^^

Why is it only printing one word of the text file rather than the whole text file to a html file

I am currently working on a project that converts a .txt file into a .xhtml file using the command line properties. Specially, this program converts an ASCII text file to an xhtml 1.0 file containing the same textual content as the original ASCII text file. The problem I seem to have is when I open the .html file to read the content from the old .txt file only one word from the file is being read into the html file. Can anyone explain why this is so? The help would be much appreciated.Thank you in advance.
//Programmer:
//Date: March 9 2015
//Purpose: converts an old style text file into any format
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <map>
using namespace std;
// getWord function to read in all words
istream& getWord(istream& is, string& word)
{
// find the beginning of the word (ie . eat all the non alphas)
char ch;
while (is.get(ch))
{
if (isalpha(ch))
break;
}
// quit if no word found
if (!is)
return is;
string buffer;
buffer += ch; // put the valid alpha onto the buffer
while (is.get(ch))
{
if (isalpha(ch))
buffer += ch;
else
break;
}
if (is)
is.unget();
if (is.eof())
is.clear();
if (is)
//word = buffer; // put the complete buffer into the word so it can be returned by reference.
//This does a copy + destroy!!
swap(word, buffer); // C++98(swap owner, then destory the old)
word = std::move(buffer); // C++ 11
return is;
}
int main(int argc, char* argv[])
{
ifstream infile(argv[1]);
char ch = 0;
while (infile.get(ch)){
cout.put(ch);
}
// print out all the command line arguments
for (size_t i = 0; i < argc; ++i)
{
string s = (string)argv[i];
cout << s << endl;
}
//if input file is at location 1 in the command line
string input = argv[1];
for (size_t i = 0; i < input.size(); ++i)
{
cout.put(input[i]);
}
cout << endl;
// Creating the html output file
ofstream out("title.html");
out << "<html xmlns=\"http://www.w3.org/1999//xhtml\"xml:lang=\"en\">" << endl;
out << "<head>" << endl;
out << "<meta http - equiv = \"Content-Type\" content = \"text/html; charset=UTF-8\" />" << endl;
out << "<title>" << argv[1] << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << argv[1] << endl;
// extracting the words from the file and storing it in a container
typedef map<string, unsigned> dictionary_type;
dictionary_type words;
// read the information in to find only words
string word;
while (getWord(infile, word))
{
auto loc = words.find(word);
if (loc == words.end())
words.insert(pair<string, int>(word, 1));
else
loc->second++;
}
//print out the container
for (auto w : words)
cout << w.first << ": " << w.second << endl;
out << "</body>" << endl << "</html>";
}
I see couple of problems:
You are reading the contents of the file first, echoing the contents to std::cout. After you are done with that, there is nothing to read from the file. Add a call to rewind the file and then read its contents again.
infile.clear(); // Clear its state. Otherwise infile.eof() is true.
infile.seekg(0); // rewind
Those lines need to go before
while (getWord(infile, word))
You have the lines:
if (is)
swap(word, buffer); // C++98(swap owner, then destory the old)
word = std::move(buffer); // C++ 11
You need to use only one of them, not both. If you use both, word gets set to an empty string.