.compare not matching a string pulled from an object - c++11

I am trying to go threw a vector of Student objects. If I find a matching ID to the one I am searching for it will display their info.
However, when I try to find a specific ID .compare isn't seeing a match even though it should.
My output: first line is the ID I am looking for, second is the current ID being looked at, then is the result of the compare.
a11111111
a22222222
-1
no match
a11111111
a11111111
-1
no match
Asked for more of the code so here is the entire program: (issue in displayID)
header file
#ifndef structures_h
#define structures_h
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <map>
using namespace std;
main program
#endif
typedef pair<string, string> Name; // first name, last name
typedef map<string, int> Grades; // map courses to scores
#include "struct.h"
class Student {
public:
void display(ostream& os) const;
void setId(string);
void setName(string, string);
void setGrades(string, int);
string getId();
string getName();
void getGrades();
bool operator<(const Student &rhs) const { return id_ < rhs.id_; }
private:
string id_; // e.g. "a22222222"
Name name_; // e.g. {"ned", "flanders"}
Grades grades_;
};
void Student::setId(string id) {
id_ = id;
}
string Student::getId() {
return id_;
}
void Student::setName(string first, string last) {
name_ = pair<string,string>(first, last);
}
string Student::getName() {
return get<0>(name_) + ' ' + get<1>(name_);
}
void Student::setGrades(string course, int score) {
grades_.insert(make_pair(course, score));
}
void Student::getGrades() {
for(auto it = grades_.begin(); it != grades_.end(); ++it) {
cout << it -> first << ' ' << it -> second << endl;
}
}
vector<Student> addStudent(int count, int x, vector<Student>& vStu, string file) {
string line, first, last;
ifstream infile(file);
while (getline(infile, line)) {
vStu.push_back(Student());
vStu[count].setId(line);
getline(infile, line);
istringstream iss(line);
if (!(iss >> first >> last)) {
cout << "failed to get name" << endl;
break;
}
vStu[count].setName(first, last);
getline(infile, line);
istringstream iss2(line);
if (!(iss2 >> x)) {
cout << "failed to get class number" << endl;
break;
}
for (int i = 0; i < x; i++) {
string sClass;
int grade;
getline(infile, line);
istringstream iss3(line);
if (!(iss3 >> sClass >> grade)) {
cout << "failed to get class and grade" << endl;
break;
}
vStu[count].setGrades(sClass, grade);
}
count++;
}
return vStu;
}
void display(vector<Student>& vStu) {
sort(vStu.begin(), vStu.end());
cout << endl;
int count = vStu.size();
for (int i = 0; i<count;i++) {
cout << vStu[i].getId() << endl;
cout << vStu[i].getName() << endl;
vStu[i].getGrades();
cout << endl;
}
}
void displayID(vector<Student>& vStu, string ID) {
int count = vStu.size();
string test;
ID = "a11111111";
for (int i = 0; i<count;i++) {
cout<< endl;
test = vStu[i].getId();
cout << ID << endl;
cout << test << endl;
cout << ID.compare(test) << endl;
if (ID.compare(test) == 0) {
cout << "match" << endl;
cout << vStu[i].getId() << endl;
cout << vStu[i].getName() << endl;
vStu[i].getGrades();
cout << endl;
} else {
cout << "no match" << endl;
}
}
cout << endl;
}
void mainMenu(vector<Student>& vStu) {
string input;
string word;
vector<string> com;
while(1) {
cout << "Enter command: ";
getline(cin,input);
istringstream iss(input);
while(iss >> word) {
com.push_back(word);
}
for (int i = 0; i < (int)com.size(); i++) {
transform(com[i].begin(), com[i].end(), com[i].begin(), ::tolower);
if (com[i] == "show") {
display(vStu);
} else if (com[i] == "showid") {
displayID(vStu, "a11111111");
}
}
com.clear();
}
}
int main(int argc, char *argv[]) {
vector<Student> vStu;
int count = 0, x = 0;
if (argc != 2) {
cout << "Incorrectly called" << endl;
cout << " " << argv[0] << ' ' << "<filename>" << endl;
return 1;
}
addStudent(count, x, vStu, argv[1]);
mainMenu(vStu);
}

The only possibility I see is that there is some whitespace at the end of the string that gets passed into your function. Try trimming the end of the string's like this this thread suggests before comparing and see if they still don't compare correctly.

Related

Unhandled exception at 0x006A549C in myApplication.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x01202FFC)

I am writing a program with C++ that needs to read a CSV file and store it in a binary search tree. But, when the program is reading the file, it fails in the library debugger.jmc.c and in the method void __fastcall __CheckForDebuggerJustMyCode(unsigned char *JMC_flag). Could someone help me? Thanks!
#include <algorithm>
#include <iostream>
#include <ctime>
#include <string>
#include "CSVparser.hpp"
using namespace std;
using namespace std;
struct Bid {
string bidId;
string title;
string fund;
double amount;
Bid() {
amount = 0.0;
}
};
struct Node {
Bid bid;
Node* left;
Node* right;
Node() {
left = nullptr;
right = nullptr;
}
Node(Bid aBid) : Node() {
this->bid = aBid;
}
};
class BinarySearchTree {
private:
Node* root;
void addNode(Node* node, Bid bid);
void inOrder(Node* node);
Node* removeNode(Node* node, string bidId);
public:
BinarySearchTree();
virtual ~BinarySearchTree();
void InOrder();
void Insert(Bid bid);
void Remove(string bidId);
Bid Search(string bidId);
Node* SearchNode(Node* node, string bidId);
};
BinarySearchTree::BinarySearchTree() {
root = nullptr;
}
/**
* Destructor
*/
BinarySearchTree::~BinarySearchTree() {
// recurse from root deleting every node
}
/**
* Traverse the tree in order
*/
void BinarySearchTree::InOrder() {
}
/**
* Insert a bid
*/
void BinarySearchTree::Insert(Bid bid) {
// FIXME (2a) Implement inserting a bid into the tree
if (root == nullptr) {
root = new Node(bid);
}
else {
addNode(root, bid);
}
}
/**
* Remove a bid
*/
void BinarySearchTree::Remove(string bidId) {
// FIXME (4a) Implement removing a bid from the tree
Node* nodePtr = SearchNode(root, bidId);
if (nodePtr == nullptr) {
return;
}
else {
//not yet implemented
}
}
/**
* Search for a bid
*/
Bid BinarySearchTree::Search(string bidId) {
// FIXME (3) Implement searching the tree for a bid
}
void BinarySearchTree::addNode(Node* node, Bid bid) {
// FIXME (2b) Implement inserting a bid into the tree))
//if node is larger than the bid add to the left subtree
if (stoi(node->bid.bidId) > stoi(bid.bidId)) {
if (node->left == nullptr) {
node->left = new Node(bid);
}
else {
addNode(node->left, bid);
}
}
//add to right subtree
else {
if (node->right == nullptr) {
node->right = new Node(bid);
}
else {
addNode(node->right, bid);
}
}
return;
}
void displayBid(Bid bid) {
cout << bid.bidId << ": " << bid.title << " | " << bid.amount << " | "
<< bid.fund << endl;
return;
}
/**
* Load a CSV file containing bids into a container
*
* #param csvPath the path to the CSV file to load
* #return a container holding all the bids read
*/
void loadBids(string csvPath, BinarySearchTree* bst) {
cout << "Loading CSV file " << csvPath << endl;
// initialize the CSV Parser using the given path
csv::Parser file = csv::Parser(csvPath);
try {
for (unsigned int i = 0; i < file.rowCount(); i++) {
// Create a data structure and add to the collection of bids
Bid bid;
bid.bidId = file[i][1];
bid.title = file[i][0];
bid.fund = file[i][8];
bid.amount = strToDouble(file[i][4], '$');
// push this bid to the end
bst->Insert(bid);
}
}
catch (csv::Error& e) {
std::cerr << e.what() << std::endl;
}
}
double strToDouble(string str, char ch) {
str.erase(remove(str.begin(), str.end(), ch), str.end());
return atof(str.c_str());
}
int main(int argc, char* argv[]) {
// process command line arguments
string csvPath, bidKey;
switch (argc) {
case 2:
csvPath = argv[1];
bidKey = "98105";
break;
case 3:
csvPath = argv[1];
bidKey = argv[2];
break;
default:
csvPath = "eBid_Monthly_Sales_Dec_2016.csv";
bidKey = "98105";
}
clock_t ticks;
// Define a binary search tree to hold all bids
BinarySearchTree* bst = nullptr;
Bid bid;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Load Bids" << endl;
cout << " 2. Display All Bids" << endl;
cout << " 3. Find Bid" << endl;
cout << " 4. Remove Bid" << endl;
cout << " 9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
bst = new BinarySearchTree();
ticks = clock();
loadBids("eBid_Monthly_Sales.csv", bst);
//cout << bst->Size() << " bids read" << endl;
// Calculate elapsed time and display result
ticks = clock() - ticks;
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 2:
bst->InOrder();
break;
case 3:
ticks = clock();
bid = bst->Search(bidKey);
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
if (!bid.bidId.empty()) {
displayBid(bid);
}
else {
cout << "Bid Id " << bidKey << " not found." << endl;
}
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 4:
bst->Remove(bidKey);
break;
}
}
cout << "Good bye." << endl;
return 0;
}

C++ .exe has stopped working - error in code

I wrote a small program in c++, and it doesn't have any error on compile time but when I run the program, I'm facing with an error.
Following is my code :
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
#include <queue>
#include "QueType.h"
#include "StackType.h"
#include "tools.hpp"
#include <locale>
#include <list>
using namespace std;
bool isPalindrome(const string& stringToCheck)
{
string line2;
bool pal;
string wrdF;
stack<char> word1;
queue<char> word2;
char x,y;
line2=stringToCheck;
// make lowercase
for (size_t j=0; j< line2.length(); ++j)
{
line2[j] = tolower(line2[j]);
}
std::locale loc;
std::string str = line2 ;
std::string::size_type al=0;
wrdF = "";
std::string::size_type al2 = 0;
while ( (al<str.length()) ) {
if (std::isalnum(str[al])) {
wrdF += str[al];
al2++;
}
++al;
}
ItemType* items = new ItemType[al2];
strcpy(items,wrdF.c_str());
int oo=(int)al2;
for (int q=0;q<oo ;q++)
{
if (items[q] != ' ') {
word1.push(items[q]);
word2.push(items[q]);
}
}
pal = true;
while (!word1.empty() && !word2.empty())
{
x=word1.top();
y=word2.front();
if (x != y)
{
cout << "No palindrome" << endl;
pal=false;
break;
}
else
{
word1.pop();
word2.pop();
}
}
if (pal == true)
cout << " palindrome" << endl;
return(pal);
}
int main()
{
int row=0;
string line;
bool pali;
ifstream myfile ("palindrome-testfile.txt");
ofstream palin("palindromes.log");
ofstream nopalin("nopalindromes.log");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
// cout << line << '\n';
++row;
// cout<<row<<". ";
pali= isPalindrome(line);
if (pali)
{
palin << line << endl;
}
else
{
nopalin << line << endl;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Please help me to resolve it. Thanks in advance.
Capture of error
As Igor Tandetnik pointed out the problem is with the ItemType pointer. Which also leaks memory.
I wrote a similar code that checks if a word is palindrome. The cppreference example for std::equal is a is_palindrome function.
I am not sure about why you need the step for std::isalnum. That one will return true for numbers too. std::isalpha will return true only if they are are letters, see cppreference doc for isalpha
Let me know if you need any clarifications.
#include <algorithm>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
bool isPalindrome(const std::string& str) {
return std::equal(str.begin(), str.begin() + str.size() / 2, str.rbegin());
}
int main() {
std::ifstream myfile("palindrome-testfile.txt");
if(!myfile.is_open()) {
std::cerr<< "Could not open file" << std::endl;
} else {
std::string word;
//operator >> will read words until you reach eof()
myfile >> word;
while(!myfile.eof()){
auto str = word;
//here I delete anything that is not alnum
str.erase(std::find_if(str.begin(), str.end(),
[](unsigned char c) { return !std::isalnum(c); }));
//Making all characters of the string lower case
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) { return std::tolower(c); });
if(isPalindrome(str)) {
std::cout << "[" << str <<"] is palindrome" << std::endl;
} else {
std::cout << "[" << str <<"] is not palindrome" << std::endl;
}
myfile >> word;
}
myfile.close();
}
return 0;
}

Not able to store data in a private member variable from a const member function - FIX8 c++

This is my header :
class my_router_client : public FIX8::my::mine_Router {
private:
mine_session_client& _session;
mutable std::vector<std::string> vSymbolList;
public:
my_router_client(mine_session_client& session) : _session(session) {}
virtual bool operator() (const FIX8::my::SecurityList *msg) const;
void sendToServer(FIX8::Message *);
void logout();
void itertool() const;
};
I am trying to save the data obtained from security list response to the vSymbolList vector. After handling security response I am trying to iterate through the vector by itertool method. But every time I end up with an empty vector. I tried printing the contents of the vector inside securitylist response function
virtual bool operator() (const FIX8::CX::SecurityList *msg) const;
and I am able to print the contents. Is it some kind of race condition inside threads?
this is the security list response handler
bool cx_router_client::operator() (const CX::SecurityList *msg) const
{
GroupBase *dad(msg->find_group< CX::SecurityList::NoRelatedSym >());
if (dad) {
for (size_t cnt(0); cnt < dad->size(); ++cnt) {
CX::Symbol symbol;
MessageBase *details(dad->get_element(cnt));
details->get(symbol);
string ss;
ss = symbol();
vSymbolList.push_back(ss);
// cout << "at :: :: " << vSymbolList[cnt] << endl;
}
cout << "no of symbol : " << vSymbolList.size() << endl;
hypersleep<h_seconds>(1);
}
return true;
}
This is the itertool method :
void my_router_client::itertool() const
{
cout << "symbol list vector size inside itertool:: " << vSymbolList.size() << endl;
stringstream ss;
ss << this_thread::get_id();
uint64_t id = stoull(ss.str());
cout << "Thread ID #### " << id << endl;
vector<string>::iterator it = this->vSymbolList.begin();
while (it != vSymbolList.end()) {
cout << *it << endl;
it++;
}
}
This is how I use the them in main :
int main()
{
const string conf_file("myfix_client.xml");
unique_ptr<ClientSessionBase> mc(new ClientSession<mine_session_client>(my::ctx(), conf_file, "DLD1"));
mc->start(false, next_send, next_receive, mc->session_ptr()->get_login_parameters()._davi());
hypersleep<h_seconds>(1);
my_router_client *test = new my_router_client(static_cast< mine_session_client& > (*mc->session_ptr()));
hypersleep<h_seconds>(1);
test->sendToServer(makeSecurityListRequest());
hypersleep<h_seconds>(1);
test->itertool();
while(1);
}

Different behavior with similar code

#include <vector>
#include <iostream>
using namespace std;
struct A
{
vector<int> v;
};
void f0(const A&& a0)
{
cout << &a0.v[0] << endl;
A a1{ move(a0.v) };
cout << &a1.v[0] << endl << endl;;
}
void f1()
{
A a0{ vector<int>(10) };
cout << &a0.v[0] << endl;
A a1{ move(a0.v) };
cout << &a1.v[0] << endl;
}
int main()
{
f0(A{ vector<int>(10) });
f1();
return 0;
}
I can't understand why in the first case addresses are different but in the second case addresses are same.

Error: Identifier "PrintGuessesRemaining" , "PrintWordSpaceDelinated" , "PrintWordsRemainingIsUndefined"

I have Created a Print Class where I have created all of those functions.
When I attempt to call these functions, I get the Identifier Error. I am sure I have incorrectly set up my class. Please Help construct Print Class
Code attached:
// Print.cpp - Print Class implementation
// Written by Varun Patel
#include "Print.h"
Print::Print()
{
}
Print::Print(const string& word)
{
Word = word;
}
void Print::PrintWordsRemaining(set<string>& possibleWords_, bool displayNumberOfWordsRemaining_)
{
if(displayNumberOfWordsRemaining_)
{
cout << "There are " << possibleWords_.size() << " possible words left." << endl;
}
else
{
//Do nothing
}
}
void Print::PrintWordSpaceDelinated(string word_)
{
for (size_t i = 0; i < word_.size(); i++)
{
cout << word_[i] << " ";
}
cout << endl;
}
void Print::PrintGuessesRemaining(int guessesRemaining_)
{
cout << "You have " << guessesRemaining_ << " guesses remaining." << endl;
}
Here is how i try to call one of the functions:
#include "UpdateGuessesRemaining.h"
void UpdateGuessesRemaining(set<string>& newPossibleWords, int& guessesRemaining,
char guessChar, string& guessedWord)
{
set<string>::iterator wordPtr = newPossibleWords.begin();
if (wordPtr->find(guessChar) == -1)
{
cout << "Sorry, incorrect guess. ";
PrintGuessesRemaining(--guessesRemaining);
}
else
{
cout << "Correct! The word contains " << guessChar << "." << endl;
}
}
Here is my header File:
// Print.h - Print Class declaration
// Written by Varun Patel
#pragma once
#include <iostream>
#include <set>
#include <string>
#include "PromptForGuessesRemaining.h"
using namespace std;
class Print
{
public:
// Default constructor
Print();
Print(const string& word);
void PrintWordsRemaining(set<string>& possibleWords, bool displayNumberOfWordsRemaining);
void PrintWordSpaceDelinated(string word);
void PrintGuessesRemaining(int guessesRemaining);
private:
string Word;
};
Thanks For Your Help,
Varun

Resources