put negative integer value in edit box in MFC? - mfc

How to put negative integer value in edit box in MFC ?
I tried using Cstring and then changing it to integer using _aoti()

Thanks for your help. I found a way to put negative numbers in the edit box .
here is the following code
//add a macro
#define INVALID_INT_MSG_EX L"Enter an integer between %d and %d."
//declare a global variable
int flag_for_negative_numbers = 0
void CTouchPanelModule::OnEnChangeTpTempValue()
{
UpdateData(true);
if (editBoxVariable_value == _T('-') && (flag_for_negative_numbers == 0))
{
flag_for_negative_numbers = 1;
}
else
{
int tempValueTouchPanel_value = _wtoi(editBoxVariable_value);
ValidateEditCtrl(ID_of_the_edit_box,
editBoxVariable_value,
MIN_value,
MAX_value, default_value);
}
}
//Below is the defination of ValidateEditCtrl() function
bool CustomDialogEx::ValidateEditCtrl(int CtrlId, int& valueToCheck, int minValue, int maxValue, CString defaultValue)
{
auto isValid = true;
UpdateData(TRUE);
if (valueToCheck < minValue || valueToCheck > maxValue)
{
CString cString;
cString.Format(INVALID_INT_MSG_EX, minValue, maxValue);
ChangeMessageBoxTitle appTitle(dlgTitle);
AfxMessageBox(cString);
GetDlgItem(CtrlId)->SetWindowText(defaultValue);
isValid = false;
}
return isValid;
}

Related

Passing char pointer to function ruins pointer

I am having some difficulties with a bluetooth/oled display displaying the right string. The goal is to read data from bluetooth, update a class variable(Music.setArtist()), and then read from that variable later(Music.getArtist()) to draw it using a draw text function.
If i only call drawText once, it works fine. More than one calls in a loop to drawText cause some undefined behavior though, which is usually the second pointer getting overwritten. This causes the pointer in drawText to be null, or some random characters, or something.
This is my music object.
#ifndef Music_h
#define Music_h
class Music {
private:
char *track,*artist,*length, *position;
int progressBar;
bool playing;
public:
Music(char* t, char* a, char* l, char* po, bool pl, int p): track(t), artist(a), length(l), position(po), playing(pl), progressBar(p){};
~Music(){};
char* getLength(){return length;}
char* getPosition(){return position;}
char* getArtist(){return artist;}
char* getTrack(){return track;}
bool getPlaying(){return playing;}
int getProgressBar(){return progressBar;}
void setLength(char * l){length = l;}
void setPosition(char *p){position = p;}
void setArtist(char *a){artist = a;}
void setTrack(char *t){track = t;}
void setPlaying(bool p){playing = p;}
void setProgressBar(int p){progressBar = p;}
};
#endif
This is my drawText function
void Display_obj::drawText(double xPos, double yPos,char str[], int stringSize, uint8_t asciiBuff)
{
bitmapLetter fnt_controller(0,0,0x00,0,0);
bitmapLetter sheldon_alph[0x5A];
fnt_controller.createDictionary(sheldon_alph,6,8);
int startX = xPos;
int startY = yPos;
for (int i=0; i < stringSize; i++){
char charAt = str[i];
uint8_t ascii = (uint8_t)charAt;
if (ascii > 0x60)
{
charAt = charAt & ~(0x20);
ascii = ascii & ~(0x20);
}
int width = sheldon_alph[ascii-asciiBuff].getWidth();
int height = sheldon_alph[ascii-asciiBuff].getHeight();
size_t siz = sheldon_alph[ascii-asciiBuff].getSize();
unsigned char* bitmap = sheldon_alph[ascii-asciiBuff].getLetter();
drawBitmap(startX,startY,width,height,bitmap,siz);
startX = startX - 8;
if (startX <= 0)
{
startX = xPos;
startY = startY+8;
}
}
}
and my main loop looks something like this
Music music("", "", "", "", false, 0);
RideTracking ride("", "", "", "", "", false);
Navigation nav("", "", "", "", "", false);
void loop(){
if (bt.getDataUpdated() == false)
{
bt.recvWithEndMarker(&bt,&music);
}
else
{
//Serial.println(music.getTrack());
musicUpdateTrack(music.getTrack());
//Serial.println(music.getArtist()); --> This returns gibberish. If the above update is commented out, it works.
musicUpdateArtist(music.getArtist());
bt.setDataUpdated(false);
}
}
Ive tried everything i can think of, which was a lot of messing around with pointers and addresses to see if it was allocated correctly. This is the closest ive gotten, but it seems like the drawText breaks the rest of the char pointers i call in the future. I dont believe the issue has to do with flash or SRAM, as both seem to be within normal values. Any help would be greatly appreciated.
EDIT: in my bluetooth object, there are two calls. one is receive the data, and the other updates the object. I originally didnt include this as it looks like data is set correctly. if i dont call drawtext, but just call print statements, the data is correct.
void blue::updateData(Music* music) {
if (getDataUpdated() == true) {
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, receivedChars);
else{
char s1[55];
char s2[55];
char s3[15];
char s4[15];
char s5[15];
if(doc["music"]) {
strlcpy(s1, doc["music"]["track"]);
music->setTrack(s1);
strlcpy(s2, doc["music"]["artist"]);
music->setArtist(s2);
strlcpy(s3, doc["music"]["track_length"]);
music->setLength(s3);
strlcpy(s4, doc["music"]["position"]);
music->setPosition(s4);
music->setProgressBar(doc["music"]["progressBar"]);
music->setPlaying(doc["music"]["playing"]);
}
}
void blue::recvWithEndMarker(blue* bt,Music* mu) {
char rc;
while (ble.available() > 0 && getDataUpdated() == false) {
rc = ble.read();;
if (rc != endMarker)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
brackets++;
if(brackets != 2)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
receivedChars[ndx] = rc;
receivedChars[ndx+1] = '\0'; // terminate the string
ndx = 0;
brackets = 0;
setDataUpdated(true);
}
}
}
bt->updateData(mu);
}
Found it! In the music class, i changed the variables such as *track, to a hardset track[50]. Then, in the set method, i changed it to
void setLength(char * l){
strlcpy(length,l,strlen(l)+1);
}
void setPosition(char *p){
strlcpy(position,p,strlen(p)+1);
}
void setArtist(char *a){
strlcpy(artist,a,strlen(a)+1);
}
void setTrack(char *t){
strlcpy(track,t,strlen(t)+1);
}
Along with a few changes in how its passed, it now works. Thanks! Ive been stuck on this for days.

Not able to see List in window initially

I want to display list items in a separate window. But when the window opens it doesn't display the list. I can click the list item but I cannot see it. If I click on data it appears one by one.Also, when I scroll down the list it displays the data.
I have tired using
m_bList_index.UpdateData(FALSE);
m_bList_index.UpdateWindow();
m_bList.UpdateData(FALSE);
m_bList.UpdateWindow();
at the last of the DisplayList() function, but that didn't resolve the issue. Below is the code which I want to edit.
CListBox m_bList_index;
CMyListBox m_bList;
BOOL CBatch::OnInitDialog()
{
CDialog::OnInitDialog();
m_status.Empty();
m_bIndex.Empty();
m_elapsed_time.Empty();
m_estimated_time.Empty();
CenterWindow();
m_bList.CreateColumn();
DisplayList();
return TRUE;
// return TRUE unless you set the focus to a control
}
void CBatch::DisplayList()
{
unsigned int size;
m_bList_title.ResetContent();
m_bList_title.SetHorizontalExtent(2000);
m_bList_title.InsertString(0, theApp.m_pFieldBTitleStr);
theApp.bCheckList->SetSortingType(theApp.checkList->GetSortingType());
theApp.bCheckList->Sort();
size = theApp.bCheckList->GetSize();
m_bList_index.SetRedraw(FALSE);
m_bList_index.ResetContent();
m_bList_index.SetHorizontalExtent(2000);
m_bList.SetRedraw(FALSE);
m_bList.DeleteAllItems();
m_bList.SetHorizontalExtent(2000);
char ColumnName[256];
char strColumnValue[256];
double fColumnValue;
for (unsigned int i = 0; i < size; i++)
{
char buffer[255];
int index = 0;
if(m_bList.m_SerialNo)
{
sprintf(buffer,"%d",i+1);
m_bList.InsertItem(i, buffer,0);
index = 0;
}
else
{
theApp.bCheckList->m_checkArray[i]->get((CV_CHECK_FIELD)(m_bList.ListColumns[0]),buffer);
m_bList.InsertItem(i, buffer,0);
index = 1;
}
for(; index < m_bList.NoofColumns; index++)
{
LV_COLUMN rightjust;
rightjust.mask = LVCF_FMT;
rightjust.fmt = LVCFMT_RIGHT;
m_bList.SetColumn(index+m_bList.m_SerialNo,&rightjust);
memset(buffer,0x0,256);
theApp.bCheckList->m_checkArray[i]->get((CV_CHECK_FIELD)(m_bList.ListColumns[index]),buffer);
if ( (m_bList.ListColumns[index] == CV_CHECK_FIELD_FILELOCATION) ||
(m_bList.ListColumns[index] == CV_CHECK_FIELD_POSTED_DATE) ||
(m_bList.ListColumns[index] == CV_CHECK_FIELD_STATUS))
strcpy(buffer, buffer);
}
m_bList.SetItemText(i,index+m_bList.m_SerialNo,buffer);
}
}
m_bList.SetSel(0, TRUE);
m_bList.SetRedraw(TRUE);
m_bList_index.SetRedraw(TRUE);
UpdateData(FALSE);
}

Can you tell me what's wrong with this implementation of Cohen-Sutherland Algorithm?

Please, help me to fix the code of this implementation of Cohen-Sutherland Algorithm.
The theory is here at Page-91.
Here is the entire project.
#include "Line2d.h"
#include "Rectangle2d.h"
#include "Coordinates2d.h"
class ClippingLine2d
{
private:
Rectangle2d rectangle;//clipping rectangle
Line2d line;//line to be clipped
private:
Bits startPointBits;//bits for start point of line
Bits endPointsBits;//bits for end point of line
public:
ClippingLine2d(Rectangle2d rect, Line2d line)
{
this->rectangle = rect;
this->line = line;
}
private:
Line2d GetClippedLine(std::vector<Line2d> clippingRegionLines, Line2d ln)
{
Point2d start = ln.GetStart();
Point2d end = ln.GetEnd();
if(startPointBits.bit4 == 1)
{
start = ln.GetIntersection(clippingRegionLines[3]);//DA
}
else if(startPointBits.bit3 == 1)
{
start = ln.GetIntersection(clippingRegionLines[1]);//BC
}
else if(startPointBits.bit2 == 1)
{
start = ln.GetIntersection(clippingRegionLines[0]);//AB
}
else if(startPointBits.bit1 == 1)
{
start = ln.GetIntersection(clippingRegionLines[2]);//CD
}
if(endPointsBits.bit4 == 1)
{
end = ln.GetIntersection(clippingRegionLines[3]);//DA
}
else if(endPointsBits.bit3 == 1)
{
end = ln.GetIntersection(clippingRegionLines[1]);//BC
}
else if(endPointsBits.bit2 == 1)
{
end = ln.GetIntersection(clippingRegionLines[0]);//AB
}
else if(endPointsBits.bit1 == 1)
{
end = ln.GetIntersection(clippingRegionLines[2]);//CD
}
return Line2d(start.Round(), end.Round());
}
public:
Line2d GetClippedLine()
{
Point2d min = rectangle.GetStart();
Point2d max = rectangle.GetEnd();
startPointBits.PointToBits(max, min, line.GetStart());
endPointsBits.PointToBits(max, min, line.GetEnd());
std::vector<Line2d> clippingRegionLines = rectangle.GetLines();
Line2d tempLine = this->line;
Bits start = startPointBits;
Bits end = endPointsBits;
while(start.IsClippingCandidate(end))
{
tempLine = GetClippedLine(clippingRegionLines, tempLine);
Point2d startP = tempLine.GetStart();
Point2d endP = tempLine.GetEnd();
start.PointToBits(max, min, startP);
end.PointToBits(max, min, endP);
Coordinates2d::Draw(tempLine);
}
return tempLine;
}
};
#define LINENUM 3
int main()
{
Line2d ln(Point2d(-120, -40), Point2d(270, 160));
Rectangle2d rect(Point2d(0, 0), Point2d(170, 120));
Coordinates2d::ShowWindow("Cohen-Sutherland Line Clipping");
Coordinates2d::Draw(ln);
Coordinates2d::Draw(rect);
ClippingLine2d clip(rect, ln);
Line2d clippedLine = clip.GetClippedLine();
Coordinates2d::Draw(clippedLine);
Coordinates2d::Wait();
return 0;
}
The GetClippedLine() is stuck in an infinite loop. Coz, Bit3 of end-point of line always remains 1..
Down-voters and close-voters, please care to leave a comment.
The == operator in your Bits class contains a bug:
bool operator == (Bits & b)
{
bool b1 = bit1 == b.bit1;
bool b2 = bit2 == b.bit2; // <-- change bit1 to bit2
bool b3 = bit3 == b.bit3; // <-- change bit1 to bit3
bool b4 = bit4 == b.bit4; // <-- change bit1 to bit4
if(b1==true && b2==true && b3==true && b4==true) return true;
else return false;
}
The operator function is called from IsClippingCandidate() inside GetClippedLine()
Also, your clipping test is comparing to zero, and returning 1 (needs to be clipped) if the end-point of the line is grater than or equal to the clipping line, which means that if it gets clipped exactly to the line it will always be 1. So, change the comparison to be greater than instead of greater than or equal.
int Sign(int a)
{
if(a>0) return 1;
else return 0;
}
Also, if you are getting inaccurate results you can try doing the clipping in floating point instead of integer, in which case you should change the type of a to float or double and add a small tolerance to the comparison e.g. if(a > 0.0001f)
The clipping function should execute as long as there are bits set in start or end, so change IsClippingCandidate to OR the two together and return false when the result is zero (no bits are set in either) and true otherwise:
bool IsClippingCandidate(Bits & bits)
{
Bits zeroBits;
Bits orredBits = *this | bits;
if(orredBits == zeroBits) return false;
else return true;
}
You can also test whether the line is completely outside the clipping region and can be discarded like this:
bool IsInvisible(Bits & bits)
{
Bits zeroBits;
Bits andedBits = *this & bits;
if(andedBits == zeroBits) return false;
else return true;
}
If both points are outside a given clipping line then the line is invisible.

random number generator error c++ MFC

I am creating a random number generator that saves Min, Max, Avg, random numbers and bubblesorted numbers to an excel file when I came across a few errors, for some reason I am unable to call this a function from c++ MFC as shown directly below, How can I make this work?
//***************Number generator function*******************
void number_Generator(double dblArray[], int length)
{
srand((unsigned)time(0));
double rndDbl;
int rndInt;
double rndAvg = 0;
int counter = 0;
double temp = 0;
Final_Avg = rndAvg / counter; // final average to display
double lDbl=0, hDbl=Random_Cap;
int lInt = 0, hInt=1;
double dblRange=(hDbl-lDbl)+1;
int intRange=(hInt-lInt)+1;
for(int index=0; index<Samples_To_Create; index++)
{
rndInt = lInt+int(intRange*rand()/(RAND_MAX + 1.0));
rndDbl = lDbl+double(dblRange*rand()/(RAND_MAX + 1.0));
// random number if statement
if (rndInt == 0){
rndDbl = -(rndDbl);
}
//start of Min/Max if statements
if (rndMin == 0){
rndMin = rndDbl;
}
else if (rndDbl < rndMin){
rndMin = rndDbl;
}
if (rndMax == 0){
rndMax = rndDbl;
}
else if (rndDbl > rndMax){
rndMax = rndDbl;
} //end of Min Max if statements
temp = rndDbl;
rndAvg += temp;
dblArray[counter] = temp;
counter++;
}
}
}
It's being called from a button click handler:
void CECET_MFC_Dialog_Based_IntroDlg::OnBnClickedCreate()
{
UpdateData(true);
number_Generator(dblArray, 100); //100 means generate 100 random numbers
UpdateData(false);
}
The public access variables are coming up as undeclared identifier, even though they are defined as shown below.
CECET_MFC_Dialog_Based_IntroDlg::CECET_344_MFC_Dialog_Based_IntroDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CECET_344_MFC_Dialog_Based_IntroDlg::IDD, pParent)
, Final_Avg(0)
, rndMax(0)
, rndMin(0)
, Samples_To_Create(0)
, Random_Cap(0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CECET_MFC_Dialog_Based_IntroDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT3, Final_Avg);
DDX_Text(pDX, IDC_EDIT4, rndMax);
DDX_Text(pDX, IDC_EDIT5, rndMin);
DDX_Text(pDX, IDC_EDIT2, Samples_To_Create);
DDX_Text(pDX, IDC_EDIT1, Random_Cap);
}
As I mentioned in my comment, you need an instance of CECET_MFC_Dialog_Based_IntroDlg to access those fields since number_Generator is not a member. Since you indicated the fields are public the simplest solution (though not the cleanest) is to change number_Generator to accept a pointer:
void number_Generator(double dblArray[], int length, CECET_MFC_Dialog_Based_IntroDlg *p)
{
// access the variables via p->Final_Avg, p->rndMin, et cetera
}
You would then call it like so:
void CECET_MFC_Dialog_Based_IntroDlg::OnBnClickedCreate()
{
UpdateData(true);
number_Generator(dblArray, 100, this); //100 means generate 100 random numbers
UpdateData(false);
}
Some of the other semantic errors I noticed in number_Generator on quick inspection:
Final_Avg = rndAvg / counter; // final average to display is being done too early, rndAvg and counter don't haven the correct values yet. This leads to division by 0.
counter is not needed, use dblArray[index] instead.
It's better to initialize rndMin and rndMax to INT_MAX and INT_MIN (or the appropriate limits from climits for the data type), respectively, and get rid of the if (rndMin == 0) and if (rndMax == 0) checks.
Your void number_Generator(double dblArray[], int length) function is accessing class members, but the function itself is not a member of that class. So make it one or pass the required parameters in....
void CECET_MFC_Dialog_Based_IntroDlg::number_Generator(double dblArray[], int length)
{
....
}

Vector of structs and custom functions acting up

I am trying to create a C++ project for my Geometry class. I want the user to be able to store and access variables. To do this, I created a struct var containing string name and float value. I have a vector < var > varList in which to hold the variables. However, upon compiling, the program doesn't function well… at all. At first, it checks to see if the variable "dog" exists, which it obviously doesn't, and finds that it does. It then tries to change the variable dog and changeVar, instead of returning ERR_NONEXISTENT, returns a proper exit status of zero. Upon checking the variable, it sees that it doesn't exist. Then, when attempting to list all variables, it creates a segmentation fault. See below:
Building Generator 1.0 Alpha
Variable Systems Test
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter a variable name:
dog
Enter a value (A FLOAT!):
2.2
Checking to see if dog exists.
It exists!
Changing variable. Function returned 0
Enter a variable to check:
dog
Variable "dog" doesn't exist!
Segmentation fault
My source is here. I am compiling with Eclipse Helios, with G++ 4.2.1, on Mac 10.6.7 Snow Leopard. What's happening?
If this doesn't work, I'll try to figure out std::map…
Also, this is only my second question here; please excuse (but notify me of) any formatting mistakes.
Thanks,
BF
EDIT: Here's some code:
vsystem.cpp
/*
* vsystem.cpp
*
* Created on: Apr 29, 2011
* Author: wjc
*/
#include <string>
#include <vector>
#include <sstream>
#include "vsystem.h"
using namespace std;
vector <var> varList;
int addVar(string varName, float value){
// Check to see if varName already exists
bool varExists = false;
for (unsigned int i=0; i<varList.size(); i++){
if (varList[i].name == varName){
varExists = true;
return ERR_VAR_EXISTS;
}
}
// Good! The variable doesn't exist yet.
var tempVar;
tempVar.name = varName;
tempVar.value = value;
varList.push_back(tempVar);
return 0;
}
int changeVar(string varName, float newValue){
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name != varName){ // If it doesn't match…
if (i == varList.size() - 1) // And it's the last one…
return ERR_NONEXISTENT; // Uh oh!
} else { // Found it!
varList[i].value = newValue;
}
}
return 0;
}
fetchResult fetchVar(string varName){
fetchResult returnValue;
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name != varName){ // If it doesn't match…
if (i == varList.size() - 1){ // And it's the last one…
returnValue.good = false; // Uh oh!
returnValue.result = -1;
} else {
returnValue.good = true;
returnValue.result = varList[i].value;
}
}
}
return returnValue;
}
bool checkVar(string varName){
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name != varName){ // If it doesn't match…
if (i == varList.size() - 1) // And it's the last one…
return false; // It's not here.
}else break;
}
return true;
}
vector < var > getVarList(){
return varList;
}
string getVarList(string varDelim, string valueDelim){
stringstream final;
for (unsigned int i=0; i<varList.size()-1; i++){
final<<varList[i].name<<valueDelim<<varList[i].value<<varDelim;
// add variable name, delim 1 (probably tab), variable value, delim 2 (probably newline)
}
final<<varList.back().name<<valueDelim<<varList.back().value;
// same, but don't add a newline (or other)
return final.str();
}
vsystem.h
/*
* vsystem.h
*
* Created on: Apr 29, 2011
* Author: wjc
*/
#include <vector>
#include <string>
#include "consts.h"
using namespace std;
#ifndef VSYSTEM_H_
#define VSYSTEM_H_
struct fetchResult {
float result;
bool good;
};
struct var {
string name;
float value;
};
int addVar(string varName, float value);
int changeVar(string varName, float newValue);
fetchResult fetchVar(string varName);
bool checkVar (string varName);
vector < var > getVarList();
string getVarList(string varDelim, string valueDelim);
#endif /* VSYSTEM_H_ */
ui.h
/*
* ui.cpp
*
* Created on: Apr 26, 2011
* Author: wjc
*/
#include <iostream>
#include <vector>
#include "filedaemon.h"
#include "vsystem.h"
using namespace std;
int runUI(){
cout << " Variable Systems Test "<<endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout << endl;
cout<<"Enter a variable name:"<<endl;
string varname;
cin>>varname;
cout<<"Enter a value (A FLOAT!):"<<endl;
float value;
cin>>value;
cout<<"Checking to see if "<<varname<<" exists."<<endl;
bool alreadythere = checkVar(varname);
alreadythere ? cout<<"It exists!"<<endl : cout<<"It doesn't exist."<<endl;
if (alreadythere){
cout<<"Changing variable. Function returned "<<changeVar(varname, value)<<endl;
} else {
cout<<"Setting variable. Function returned "<<addVar(varname, value)<<endl;
}
cout<<"Enter a variable to check:"<<endl;
string varcheck;
cin>>varcheck;
fetchResult result = fetchVar(varcheck);
if(! result.good){
cout<<"Variable \""<<varcheck<<"\" doesn't exist!"<<endl;
} else {
cout<<"Variable \""<<varcheck<<"\" is equal to "<<result.result<<endl;
}
cout<<getVarList("\n","\t")<<endl;
string exitstr;
cin>>exitstr;
return 0;
}
main.cpp just calls runUI()
The way you are looping on the vector and returning true/false is weird and your app is crashing because of checkVar().
I encourage you to change all the loops on varList that search for an item to something more simple and easier to read, like:
bool checkVar(string varName)
{
// Check to see if varName exists
for (unsigned int i=0; i<varList.size(); i++)
{
if (varList[i].name == varName)
{ // If matches,
return true;
}
}
// If execution reaches here, it means it didn't found a match
return false;
}
This solves the crash. I don't know if your application has any other bugs, but this is my current output:
Building Generator 1.0 Alpha
Variable Systems Test
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter a variable name:
dog
Enter a value (A FLOAT!):
2.2
Setting variable. Function returned 0
Enter a variable to check:
alpha
Variable "alpha" doesn't exist!
dog 2.2
EDIT:
Another problem is with your defines: ERR_NONEXISTENT and ERR_VAR_EXISTS are both 1. They should have different values! I'm pasting the relevant code below:
consts.h:
#ifndef CONSTS_H_
#define CONSTS_H_
#define VERSION "1.0 Alpha"
// Variable errors
#define ERR_NONEXISTENT 0
#define ERR_VAR_EXISTS 1
// File r/w errors
#define ERR_FILE_OPEN 2
#endif /* CONSTS_H_ */
vsystem.cpp:
#include <string>
#include <vector>
#include <sstream>
#include "vsystem.h"
using namespace std;
vector <var> varList;
int addVar(string varName, float value){
// Check to see if varName already exists
bool varExists = false;
for (unsigned int i=0; i<varList.size(); i++){
if (varList[i].name == varName){
varExists = true;
return ERR_VAR_EXISTS;
}
}
// Good! The variable doesn't exist yet.
var tempVar;
tempVar.name = varName;
tempVar.value = value;
varList.push_back(tempVar);
return ERR_NONEXISTENT;
}
int changeVar(string varName, float newValue){
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name == varName)
{ // If it match, replace the value
varList[i].value = newValue;
return ERR_VAR_EXISTS;
}
}
return ERR_NONEXISTENT; // Uh oh!
}
fetchResult fetchVar(string varName){
fetchResult returnValue;
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name == varName){ // If it matches
if (i == varList.size() - 1)
{
returnValue.good = true;
returnValue.result = varList[i].value;
return returnValue;
}
}
}
returnValue.good = false; // Uh oh!
returnValue.result = -1;
return returnValue;
}
bool checkVar(string varName)
{
// Check to see if varName exists
for(unsigned int i=0; i<varList.size(); i++){
if(varList[i].name == varName)
{ // If matches, return true
return true;
}
}
// If execution reaches here, it means it didn't found a match
return false;
}
vector < var > getVarList(){
return varList;
}
string getVarList(string varDelim, string valueDelim){
stringstream final;
for (unsigned int i=0; i<varList.size()-1; i++){
final<<varList[i].name<<valueDelim<<varList[i].value<<varDelim;
// add variable name, delim 1 (probably tab), variable value, delim 2 (probably newline)
}
final<<varList.back().name<<valueDelim<<varList.back().value;
// same, but don't add a newline (or other)
return final.str();
}