I apologize. I just realized I posted code for this 5 years ago and I somehow answered my own question ... 5 years ago. >.>
TheFueley 0 Light Poster
I remember doing a class to handle rational numbers in one of my classes way back when. I decided to do it again. What I'm having trouble understanding right now is why do I even create a class when my overloaded functions are all friend functions? As I understand it, in order to be able to do this fractionA + fractionB, you must use a non-member function. So that meant to me, a friend function. Am I wrong in thinking this? Non-static member functions take one argument and the left argument must be an object of the class that the function is a member of. With that said, am I able to use a non-static member function and still use something like this "fractionA + fractionB"? I'm not sure how I can. Here is what my class looks like. Looking at it, it just seems strange to me to define a class and have all those friend functions since they aren't member functions of the class.
#ifndef RATIONAL_H
#define RATIONAL_H
#include <iostream>
class Rational
{
public:
Rational();
Rational(int, int);
~Rational();
// overloaded operators
friend std::ostream &operator<<(std::ostream &, const Rational &);
friend std::istream &operator>>(std::istream &, Rational &);
//Rational operator+(Rational);
friend Rational operator+(Rational, Rational);
friend Rational operator-(Rational, Rational);
friend Rational operator*(Rational, Rational);
private:
int numerator;
int denominator;
// helper functions
void simplify();
friend int GCD(int, int);
friend int LCM(int, int);
};
#endif
TheFueley 0 Light Poster
That was exactly what I was looking for. Thank you!
TheFueley 0 Light Poster
I'm having trouble figuring out how to use exceptions to check if a file stream was created successfully. I know I can use if statements, but how do I do this using try/catch statements? It compiles successfully but it gives me an error when I supply a non-existent filename as an argument. If I supply a file that does exist, it runs fine. The message I get when I give it a bogus filename is:
terminate called after throwing an instance of 'char*'
Abort trap
#include <iostream>
#include <fstream>
#include <exception>
int main(int argc, char *argv[])
{
try
{
std::ifstream somefile(argv[1], std::ios::in | std::ios::binary);
if (somefile.good())
std::cout << "Opened file!";
else
throw "Error opening file!";
somefile.close();
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
exit(1);
}
return 0;
}
TheFueley 0 Light Poster
Hello Salem,
I'm thinking I could use atoi to convert the third arg to an int.
int key = atoi(argv[3]);
.
.
.
// XOR
for (int i=0; i<size; i++)
memblock[i] ^= key;
How would I process the file block by block?
Could I figure out the file size, process say 100 bytes at a time, update file pointer to 100 bytes later in the file? process data again until eof is reached? If there are less than 100 bytes in last read of file, then use that amount to process? Is that right?
BTW, I like your avatar.
TheFueley 0 Light Poster
Hello,
This is how I went about XOR'ing a binary file and outputting to another file the XORed contents. Does anybody see anything wrong with this approach or something I should do differently? I was able to reapply the XOR to the "encrypted" file and receive a valid jpg back from it. Compiled and ran fine on Redhat and XP. Usage
xor inputfile outputfile key
#include <iostream>
using std::ios;
using std::cout;
using std::endl;
#include <fstream>
using std::ofstream;
using std::ifstream;
int main(int argc, char *argv[])
{
// open plaintext file
ifstream plainFile(argv[1], ios::in | ios::ate | ios::binary);
char *memblock;
if (plainFile.is_open())
{
ifstream::pos_type size = plainFile.tellg();
memblock = new char [size];
plainFile.seekg(0, ios::beg);
plainFile.read(memblock, size);
plainFile.close();
cout << "Plaintext file contents in memory" << endl;
// create output filestream
ofstream encryptedFile(argv[2], ios::out | ios::binary);
cout << "XOR\'ing the buffer" << endl;
// XOR the chars
for (int i = 0; i < size; i++)
memblock[i] ^= *(argv[3]);
// write buffer to file
cout << "Writing to \"encrypted file\"" << endl;
encryptedFile.write(memblock, size);
delete [] memblock;
plainFile.close();
encryptedFile.close();
}
// error opening file
else
cout << "Couldn't open file" << endl;
return 0;
}
TheFueley 0 Light Poster
That worked great. Thank you!
TheFueley 0 Light Poster
Sweet! I will give it a try. In the mean time, I used a loop to String.Compare each item. Not what I wanted though. Thanks for the tip!
TheFueley 0 Light Poster
How do you guys recommend searching an ArrayList for a specific string? My arraylist is defined as:
Public Shared VisioSwitchArray As New ArrayList()
Public Structure switch
Public HOSTNAME As String
Public IP As String
Public MODEL As String
Public VLANS As String
Public NEIs() As neighbor
End Structure
Public Structure neighbor
Public IFACE As String
Public DIST_IP As String
Public DIST_IFACE As String
End Structure
What I'm trying to compare is the IP string from the switch structure and the DIST_IP string from the neighbor structure. Problem is, using VisioSwitchArray.contains(some_ip_address) always returns false. I'm guessing it is searching for a matching switch object with in the list right?
TheFueley 0 Light Poster
I was stepping through the code in a debugger and found that when I do it that way, I dont have to hit ENTER twice. For some reason, it works properly in the debugger. I think this may be a timing issue.
TheFueley 0 Light Poster
Plink is a command-line version of PuTTY, a Windows SSH client program. I am trying to get the output from plink to display in a textbox within a VB form. I can get it to work but I must hit the ENTER key twice before it shows anything, everytime. So I end up with repeated commands thrown at plink. Anyone know why I'm seeing this?
Imports System.Text
Imports System.IO
Public Class Form1
' Define static variables shared by class methods.
Private Shared shellOutput As StringBuilder = Nothing
Private Shared numOutputLines As Integer = 0
Private Shared stdIN As StreamWriter
Private Shared p As New Process
Private Shared Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
stdIN.WriteLine(Form1.txtSend.Text.ToString)
'stdIN.Flush()
Form1.txtReceive.Text = shellOutput.ToString
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim p_info As New ProcessStartInfo
p_info.FileName = "C:\plink.exe"
p_info.Arguments = " -l username -pw password host"
p_info.UseShellExecute = False
p_info.CreateNoWindow = True
p_info.RedirectStandardOutput = True
p_info.RedirectStandardInput = True
' Set our event handler to asynchronously read the shell output.
AddHandler p.OutputDataReceived, AddressOf dirOutputHandler
shellOutput = New StringBuilder
p.StartInfo = p_info
p.Start()
stdIN = p.StandardInput
p.BeginOutputReadLine()
System.Threading.Thread.Sleep(5000)
txtReceive.Text = shellOutput.ToString
End Sub
Private Shared Sub dirOutputHandler(ByVal sendingProcess As Object, ByVal outLine As DataReceivedEventArgs)
' Collect the sort command output.
If Not String.IsNullOrEmpty(outLine.Data) Then
numOutputLines += 1
' Add the text to the collected output.
shellOutput.Append(Environment.NewLine + outLine.Data)
End If
End Sub
End Class
TheFueley 0 Light Poster
You may try
SendKeys.Send("TEXT FROM VB")
instead ofstdINwriter.WriteLine("TEXT FROM VB")
SendKeys.Send() sends keystrokes to the active window. However, it's not a very reliable method. If the process you started loses focus, it won't receive those keystrokes.
SendKeys is working for me. I make the window active first then make the call to SendKeys.
TheFueley 0 Light Poster
Hello,
I'm having trouble writing to a file. I can open notepad ok, but I cannot write a string to it. What am missing here? TIA.
Imports System.IO
Module Module1
Sub Main()
Dim start_info As New ProcessStartInfo("notepad.exe")
start_info.UseShellExecute = False
start_info.ErrorDialog = False
start_info.RedirectStandardInput = True
start_info.RedirectStandardOutput = True
start_info.RedirectStandardError = True
Dim proc As New Process
proc.StartInfo = start_info
proc.Start()
Dim stdERRreader As StreamReader = proc.StandardError
Dim stdINwriter As StreamWriter = proc.StandardInput
Dim stdOUTreader As StreamReader = proc.StandardOutput
System.Threading.Thread.Sleep(500)
' send data
stdINwriter.WriteLine("TEXT FROM VB")
stdINwriter.Flush()
stdINwriter.Dispose()
' clean up
stdERRreader.Close()
stdINwriter.Close()
stdOUTreader.Close()
proc.WaitForExit()
End Sub
End Module
TheFueley 0 Light Poster
Oh okay. Thank you ArkM that does help.
TheFueley 0 Light Poster
Interesting. I was mistakenly under the impression that a Linked list is just collection of nodes. Could you show me how I should be going about this? If you don't mind. I keep googling "linked list" and I only find examples using structs. Then I decided to go about it in a class, just to practice and whatnot. Thanks for your help.
Declare
const Node* temp
in const member functions - that's all. These functions must not modify Node fields but you can modify them viaNode* temp
pointer.Yet another remark:
Did you want to implement Linked List class? If so why did you implement Node only class? A list is not a simple Node. Now you are trying to manipulate with list via Node pointers only in C (not C++ ) style. It's an example of a bad class design...
TheFueley 0 Light Poster
Yes, I've been reading that FAQ site. I got the idea from that site that if you create a function that *should not* modify the members it deals with you can/should declare it const. I also read that the const_cast is not preferred or dangerous? I'm just trying to learn the proper way to do this and since this is not a school project, I'm being a little picky about it. I appreciate your help. I will probably give up and make is simpler in the end anyway.
You can use const_cast, i.e.
Node * temp = const_cast<Node*>(this);
Maybe you could revise the 'constness' of the code (I did not look too closely). Perhaps read about Const correctness.
TheFueley 0 Light Poster
Hmm. I thought having two pointers, one to the previous node and one to the next node qualified this as a doubly-linked list. I could be wrong.
From the header file
private: Node *previous, *next; string first, last;
Also, thank you for your help.
TheFueley 0 Light Poster
I'm a little confused on your reply.
You have a pointer-to-Node to track the beginning of the list but the beginning can change throughout the code. What was the first object may not always be the first object. That's why I have it find the first object and start from there. Then on lines 10-12 of your code you show a while-loop to print all the objects, but it wont print the last object as it is typed. On the last Node, list->next will point to NULL so the while condition test fails and moves on without printing the last object.
What my question really was about is how do I convert a const Node *const to Node*? The this pointer is type const Node *const. I apologize if I wasn't clear from the start.
Your function is a bit, no way too complicated >_>, just keep one pointer to track the first link of your list and reference it when you want to print it.
Node *list, *front, *temp; list = new struct node; front = list //your code here, do not modify "front" list = front; //print from begining while(list != NULL) cout<<list->data; list = list->next;
TheFueley 0 Light Poster
Hello all,
I am trying to make a linked list (class-based). I'm not sure if I went actually did it right. I get a compiler error on the segment of code that deals with printing the linked list to stdout. Here is the seqment in question.
// print contents of list
void Node::printAll() const
{
Node *temp = NULL;
temp = this;
if (temp->previous != NULL)
temp = findFirst(temp);
else
{
do
{
// prints all items except last
// since it tests for next to point to NULL
cout << temp->first << " " << temp->last << endl;
if (temp->next == NULL)
continue;
else
temp = temp->next;
} while (temp->next != NULL);
}
// print last item
cout << temp->first << " " << temp->last << endl;
}
The error my compiler displays is
"cannot convert from const Node *const to Node* Conversion loses qualifiers". I'm not sure how to fix this.
And here is the whole thing for reference.
#ifndef NODE_H
#define NODE_H
#include <string>
using std::string;
class Node
{
public:
Node();
Node* addToFront(Node*);
Node* addToBack(Node*);
Node* findFirst(Node*) const;
Node* findLast(Node*) const;
void printAll() const;
private:
Node *previous, *next;
string first, last;
void collectData(Node*);
};
#endif
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <string>
using std::string;
#include "Node.h"
Node::Node() : previous(NULL), next(NULL)
{
collectData(this);
}
// add new Node to beginning
Node* Node::addToFront(Node *n)
{
Node *temp = new Node;
n = findFirst(n);
temp->next = n;
n->previous = temp;
return …
TheFueley 0 Light Poster
Yes, the Distro List is in the GAL. I just cannot find any tutorials on the net for getting started. Thanks for your reply
TheFueley 0 Light Poster
Hello all,
I want to programmatically add users to a distro list in Outlook 2003(server). I haven't been able to find a suitable solution nor have I been able to even determine which language to use. I'm guessing that C# could be used. Anyone know of any examples of this? I have only found tips on "Creating Distro Lists". My lists are already created though. Thanks in advance!
TheFueley 0 Light Poster
Wow, I forgot about that. Thank you!
TheFueley 0 Light Poster
I'm trying to work out what should be a simple composition example. For some reason I can't compile this project though. I get three errors when I try to compile. Errors listed below. Where am I going wrong?
1>c:\documents and settings\user\my documents\visual studio 2008\projects\name\name\ssn.h(5) : error C2011: 'SSN' : 'class' type redefinition
1>c:\documents and settings\user\my documents\visual studio 2008\projects\name\name\name.cpp(9) : error C2027: use of undefined type 'SSN'
1>c:\documents and settings\user\my documents\visual studio 2008\projects\name\name\name.cpp(9) : fatal error C1903: unable to recover from previous error(s); stopping compilation
//Name.h
#include <string>
using std::string;
#include "SSN.h"
class Name
{
public:
Name();
Name(const string &, const string &);
Name(const string &, const string &, const SSN &);
string getFIRST() const;
string getLAST() const;
void setFIRST(const string &);
void setLAST(const string &);
private:
string FIRST;
string LAST;
const SSN SSAN;
};
//Name.cpp
#include <string>
using std::string;
#include "Name.h"
#include "SSN.h"
Name::Name()
: SSAN("000-00-0000")
{
setFIRST("Joe");
setLAST("Cool");
}
Name::Name(const string &f, const string &l)
: SSAN("000-00-0000")
{
setFIRST(f);
setLAST(l);
}
Name::Name(const string &f, const string &l, const SSN &s)
: SSAN(s)
{
setFIRST(f);
setLAST(l);
}
string Name::getFIRST() const
{
return FIRST;
}
string Name::getLAST() const
{
return LAST;
}
void Name::setFIRST(const string &f)
{
FIRST = f;
}
void Name::setLAST(const string &l)
{
LAST = l;
}
//SSN.h
#include <string>
using std::string;
class SSN
{
public:
SSN();
SSN(const string &);
void setSSN(const string &);
string getSSN() const;
private:
string SOCIAL;
};
//SSN.cpp
#include <string>
using std::string;
#include "SSN.h"
SSN::SSN()
{
setSSN("000-00-0000"); …
TheFueley 0 Light Poster
Oh my ... Wow, thank you!
TheFueley 0 Light Poster
This one of those typical Rational number programs. It takes a user-supplied fraction and then another. Then it does the 4 basic math operations on it. Finally it compares the fractions to each other. I have the program working fine. I just want to know how to fix this warning message. I don't quite know "what to return" from this block of code. TIA!
Wow, after all that I forgot to add the warning message:
warning: control reaches end of non-void function
//allows cin >> f; (f is a fraction)
istream &operator>>(istream &input, Rational &f)
{
string stringy;
//stringify the input stream
input >> stringy;
//find where the "/" is at in the string
int marker = stringy.find_first_of("/");
//numerator is from start of number to "/"
string top = stringy.substr(0, marker);
//denominator is from "/" to end
string bottom = stringy.substr(marker + 1, stringy.size() - marker);
//convert strings to ints
istringstream up(top);
int topper;
up >> topper;
istringstream low(bottom);
int lower;
low >> lower;
//set fraction
f.numer = topper;
f.denom = lower;
}
Here is all the code, for reference. It is separated into 3 files. Header, implementation, and driver.
//Rational.h
#ifndef RATIONAL_H_
#define RATIONAL_H_
#include <iostream>
using std::istream;
using std::ostream;
class Rational
{
friend istream &operator>>(istream &, Rational&);
friend ostream &operator<<(ostream &, const Rational&);
public:
Rational(int = 0, int = 1);
Rational operator+(const Rational &);
Rational operator-(const Rational &);
Rational operator*(const Rational &);
Rational operator/(const Rational &);
bool operator==(const Rational &) const;
bool operator!=(const Rational …
TheFueley 0 Light Poster
Oh! That makes sense, that didn't even occur to me. Sounds good to me, thanks!
TheFueley 0 Light Poster
When I have sizeof(utmp)
, 384 is returned. So when I try to find out the size of the individual members, I get a different result. Using the method below, I come up with 382 bytes. Anyone know where I'm missing the other 2 bytes?
#include <iostream>
using std::cout;
using std::endl;
#include <utmp.h>
void size();
int main()
{
size();
return 0;
}
void size()
{
utmp uLine;
cout << "ut_type: " << sizeof(uLine.ut_type) << " bytes." << endl;
cout << "ut_pid: " << sizeof(uLine.ut_pid) << " bytes." << endl;
cout << "ut_line: " << sizeof(uLine.ut_line) << " bytes." << endl;
cout << "ut_id: " << sizeof(uLine.ut_id) << " bytes." << endl;
cout << "ut_user: " << sizeof(uLine.ut_user) << " bytes." << endl;
cout << "ut_host: " << sizeof(uLine.ut_host) << " bytes." << endl;
cout << "ut_session: " << sizeof(uLine.ut_session) << " bytes." << endl;
cout << "ut_tv: " << sizeof(uLine.ut_tv) << " bytes." << endl;
cout << "ut_addr_v6: " << sizeof(uLine.ut_addr_v6) << " bytes." << endl;
cout << "ut_exit: " << sizeof(uLine.ut_exit) << " bytes." << endl;
cout << "ut__unused: " << sizeof(uLine.__unused) << " bytes." << endl;
}
TheFueley 0 Light Poster
How would I display an IP address from /var/log/wtmp? I know I could use utmpdump, but that's not what I'm going for. I have included bits/utmp.h and can display other members of the struct, but when i try to display the ut_addr_v6 member, I get a random hex address instead. Any thoughts?
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
using std::ios;
using std::left;
#include <utmp.h>
#include <iomanip>
using std::setw;
#include <cstdlib>
using std::exit;
#include <fstream>
using std::ifstream;
using std::ostream;
void outputLine(ostream&, const struct utmp);
int main()
{
//open log file
ifstream logfile("wtmp", ios::in | ios::out | ios::binary);
if (!logfile)
{
cerr << "File Could Not Be Opened" << endl;
exit(1);
}
struct utmp log;
logfile.read(reinterpret_cast<char *>(&log), sizeof(struct utmp));
while (logfile && !logfile.eof())
{
if (log.ut_type != 0)
outputLine(cout, log);
logfile.read(reinterpret_cast<char *>(&log), sizeof(struct utmp));
}
return 0;
}
void outputLine(ostream &output, const struct utmp record)
{
output << "USER: " << setw(15) << left << record.ut_user
<< "HOST: " << setw(25) << record.ut_host
<< "IP: " << setw(15) << record.ut_addr_v6 << endl;
}
TheFueley 0 Light Poster
I see. I guess that's why the book example used a char array as well. Thank You!
TheFueley 0 Light Poster
I'm trying to figure out how to write an int (as a record number) and a string (up to 12 characters) into a binary file. So in one project the binary file is created with all 5 records written to it, with blank data, eg string is empty. In the next project I ask for user input indicating which record to update and what string to store in the file. Then the next project displays only the records that have data stored in them.
The problem I'm having is, I think I'm writing the string to the file incorrectly. When I run the ReadBinaryFile program, it displays the record numbers correctly, but blank data for the string entries. How do I properly store a random-sized string, up to 12 characters into this file? I have posted the files I have as well.
Here is the part where I store the data to the file:
Rivera rivy;
int recordNum;
cin >> recordNum;
...
cout << "Enter word\n? ";
cin >> word;
rivy.setKey(recordNum);
rivy.setWord(word, 0, 12);
lamefile.seekp((rivy.getKey() - 1) * sizeof(Rivera));
//rivy is a Rivera obj; Rivera object contains an int and a string
lamefile.write(reinterpret_cast<const char*>(&rivy), sizeof(Rivera));
cout << "Enter Record Number: (1-5, 0 to quit0\n? ";
cin >> recordNum;
PS: This isn't homework. I am following along in C++ How to Program 5th Ed. There is a code complete exercise in the book. I am trying to do this using strings though, rather than const char*. Since it's …
#include <iostream>
using std::cerr;
using std::endl;
using std::ios;
#include <fstream>
using std::ofstream;
#include <cstdlib>
using std::exit;
#include "Rivera.h"
int main()
{
//name of ofstream object
ofstream lamefile("stringy.bin", ios::binary);
//exit if couldn't create file
if (!lamefile)
{
cerr << "Couldn't Open File." << endl;
exit(1);
}
//blank Rivera object
Rivera blankRivera;
//create 5 blank records
for (int i=0; i<5; i++)
{
lamefile.write(reinterpret_cast<const char*>(&blankRivera), sizeof(Rivera));
}
return 0;
}
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
using std::ios;
#include <fstream>
using std::ifstream;
using std::ostream;
#include <cstdlib>
using std::exit;
#include <string>
using std::string;
#include "Rivera.h"
void outputLine(ostream&, const Rivera&);
int main()
{
ifstream lamefile("stringy.bin", ios::in);
if (!lamefile)
{
cerr << "Couldnt open file." << endl;
exit(1);
}
cout << "Record Number\t\t\t" << "String" << endl;
Rivera person;
lamefile.read(reinterpret_cast<char *>(&person), sizeof(Rivera));
while (lamefile && !lamefile.eof())
{
if (person.getKey() != 0)
outputLine(cout, person);
lamefile.read(reinterpret_cast<char *>(&person), sizeof(Rivera));
}
return 0;
}
void outputLine(ostream &output, const Rivera & record)
{
output << record.getKey() << "\t\t\t" << record.getWord() << endl;
}
#include <string>
using std::string;
#include "Rivera.h"
Rivera::Rivera()
: id(0), palabra("")
{
//empty body
}
//set record num
void Rivera::setKey(const int key)
{
id = key > 0 ? key : 0;
}
//return record num
int Rivera::getKey() const
{
return id;
}
//set string
void Rivera::setWord(const string& word)
{
int start = 0;
int end = word.length() > 13 ? word.length() : 12;
string temp(word, start, end);
palabra = temp;
}
//return string
string Rivera::getWord() const
{
return palabra;
}
#ifndef RIVERA_H_
#define RIVERA_H_
#include <string>
using std::string;
class Rivera
{
public:
Rivera();
void setKey(const int);
int getKey() const;
void setWord(const string&);
string getWord() const;
private:
int id;
string palabra;
};
#endif /*RIVERA_H_*/
#include <iostream>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ios;
#include <fstream>
using std::fstream;
#include <cstdlib>
using std::exit;
#include <string>
using std::string;
#include "Rivera.h"
int main()
{
fstream lamefile("stringy.bin", ios::in | ios::out | ios::binary);
//exit if fstream cannot open file
if (!lamefile)
{
cerr << "Couldn't Open File." << endl;
exit(1);
}
cout << "Enter Record Number: (1-5, 0 to quit)\n? ";
Rivera rivy;
int recordNum;
cin >> recordNum;
string word;
while (recordNum > 0 && recordNum <= 5)
{
cout << "Enter word\n? ";
cin >> word;
rivy.setKey(recordNum);
rivy.setWord(word, 0, 12);
lamefile.seekp((rivy.getKey() - 1) * sizeof(Rivera));
lamefile.write(reinterpret_cast<const char*>(&rivy), sizeof(Rivera));
cout << "Enter Record Number: (1-5, 0 to quit0\n? ";
cin >> recordNum;
}
return 0;
}