C++ run error: pointer being freed was not allocated [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm learning c++ and am working on a program that keeps giving me a 'pointer being freed was not allocated' error. It's a grocery store program that inputs data from a txt file, then user can enter item# & qty. I've read through similar questions but what's throwing me off is the 'pointer' issue. I would appreciate if someone could take a look and help me out. I'm using Netbeans IDE 7.2 on a Mac.
I'll just post the whole piece I have so far. Thx.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Product
{
public:
// PLU Code
int getiPluCode()
{
return iPluCode;
}
void setiPluCode( int iTempPluCode)
{
iPluCode = iTempPluCode;
}
// Description
string getsDescription()
{
return sDescription;
}
void setsDescription( string sTempDescription)
{
sDescription = sTempDescription;
}
// Price
double getdPrice()
{
return dPrice;
}
void setdPrice( double dTempPrice)
{
dPrice = dTempPrice;
}
// Type..weight or unit
int getiType()
{
return iType;
}
void setiType( int iTempType)
{
iType = iTempType;
}
// Inventory quantity
double getdInventory()
{
return dInventory;
}
void setdInventory( double dTempInventory)
{
dInventory = dTempInventory;
}
private:
int iPluCode;
string sDescription;
double dPrice;
int iType;
double dInventory;
};
int main ()
{
Product paInventory[21]; // Create inventory array
Product paPurchase[21]; // Create customer purchase array
// Constructor to open inventory input file
ifstream InputInventory ("inventory.txt", ios::in);
//If ifstream could not open the file
if (!InputInventory)
{
cerr << "File could not be opened" << endl;
exit (1);
}//end if
int x = 0;
while (!InputInventory.eof () )
{
int iTempPluCode;
string sTempDescription;
double dTempPrice;
int iTempType;
double dTempInventory;
InputInventory >> iTempPluCode >> sTempDescription >> dTempPrice >> iTempType >> dTempInventory;
paInventory[x].setiPluCode(iTempPluCode);
paInventory[x].setsDescription(sTempDescription);
paInventory[x].setdPrice(dTempPrice);
paInventory[x].setiType(iTempType);
paInventory[x].setdInventory(dTempInventory);
x++;
}
bool bQuit = false;
//CREATE MY TOTAL VARIABLE HERE!
int iUserItemCount = 0;
do
{
int iUserPLUCode;
double dUserAmount;
double dAmountAvailable;
int iProductIndex = -1;
//CREATE MY SUBTOTAL VARIABLE HERE!
while(iProductIndex == -1)
{
cout<<"Please enter the PLU Code of the product."<< endl;
cin>>iUserPLUCode;
for(int i = 0; i < 21; i++)
{
if(iUserPLUCode == paInventory[i].getiPluCode())
{
dAmountAvailable = paInventory[i].getdInventory();
iProductIndex = i;
}
}
//PLU code entry validation
if(iProductIndex == -1)
{
cout << "You have entered an invalid PLU Code.";
}
}
cout<<"Enter the quantity to buy.\n"<< "There are "<< dAmountAvailable << "available.\n";
cin>> dUserAmount;
while(dUserAmount > dAmountAvailable)
{
cout<<"That's too many, please try again";
cin>>dUserAmount;
}
paPurchase[iUserItemCount].setiPluCode(iUserPLUCode);// Array of objects function calls
paPurchase[iUserItemCount].setdInventory(dUserAmount);
paPurchase[iUserItemCount].setdPrice(paInventory[iProductIndex].getdPrice());
paInventory[iProductIndex].setdInventory( paInventory[iProductIndex].getdInventory() - dUserAmount );
iUserItemCount++;
cout <<"Are you done purchasing items? Enter 1 for yes and 0 for no.\n";
cin >> bQuit;
//NOTE: Put Amount * quantity for subtotal
//NOTE: Put code to update subtotal (total += subtotal)
// NOTE: Need to create the output txt file!
}while(!bQuit);
return 0;
}

iUserItemCount is never initialised. You're invoking undefined behaviour when you use it as an index.

Because you work with statically allocated arrays you probably stumbled upon writing after the end of the array.
You state that the file has exactly 21 entries but what happens with the eof condition? If you read the last entry, the stream still doesn't have the eof bit set. This only happens when you try to read and there is nothing.
After the 21st entry, the loop still continues because the eof bit is not set. It reads garbage information and tries to store it into paInventory[21], but the array was only 21 in size.
//after last read x=21 and eof not set
while (!InputInventory.eof () )
{
//first read causes eof to be set
InputInventory >> iTempPluCode >> sTempDescription >> dTempPrice >> iTempType >> dTempInventory;
//Accessing paInventory[21] here which causes your error
paInventory[x].setiPluCode(iTempPluCode);
//...//
}

Related

What is the problem I am having with using arrays with classes?

I have been working on a project for my computer science class and have encountered an issue with the code working. I am shown no error except when I try to compile and I get an error that reads:
Exception thrown: write access violation.
_Left was 0xCCCCCCCC.
The purpose of my project is to take a list of names from an external file, read them into an array, sort said array and then output the sorted list all while using a class for the code.
Here is a copy of my code and I would like to extend my gratitude to whoever can help me through my issue:
**Header File**
#include <iostream>
using namespace std;
class person
{
public:
person();
bool get(ifstream&);
void put(ofstream&);
private:
int capacity = 0;
string first_name[CAPACITY];
string last_name[CAPACITY];
int age[CAPACITY];
};```
**Header function definitions cpp file**
#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
const int CAPACITY=20;
using namespace std;
#include "Person.h"
//Names constructor
//Postcondition both first name and last name initialized to zero
person::person()
{
first_name[CAPACITY] = "";
last_name[CAPACITY] = "";
age[CAPACITY]=0;
}
bool person::get(ifstream& in)
{
in >> first_name[CAPACITY] >> last_name[CAPACITY] >> age[CAPACITY];
return(in.good());
}
void person::put(ofstream &out)
{
out << first_name[CAPACITY] << last_name[CAPACITY] << age[CAPACITY];
}
**cpp file which holds main**
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
const int CAPACITY = 20;
using namespace std;
#include "Person.h"
void pop(string *xp, string *yp);
void sort(string name[CAPACITY], int count);
int main()
{
class person names[CAPACITY];
ifstream infile;
ofstream outfile;
string filename;
string name[CAPACITY];
int n = 0;
cout << "Enter the file name you wish to open" << endl;
cin >> filename;
infile.open(filename + ".txt");
outfile.open("Person_New.txt");
if (infile.fail())
{
cout << "The file requested did not open" << endl;
exit(1);
}
while (!infile.eof())
{
names[n].get(infile);
n++;
}
sort(name, CAPACITY);
for (int i = 0; i < CAPACITY; i++)
{
names[i].put(outfile);
}
cout << "The file has been created" << endl;
infile.close();
}
void pop(string *xp, string *yp)
{
string temp = *xp;
*xp = *yp;
*yp = temp;
}
void sort(string name[CAPACITY], int count)
{
int i, j;
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - i - 1; j++)
{
if (name[j] > name[j + 1])
{
pop(&name[j], &name[j + 1]);
}
}
}
}
Once again Thank you for any support
It sounds to me like the compiler is getting upset that you are trying to write (i.e. assign a value) at an address that you do not have permission to access. I believe your constructor for the class person might be at fault because of how this class stores its variables, as well as the class header:
Constructor for the class person:
`person::person(){
first_name[CAPACITY] = "";
last_name[CAPACITY] = "";
age[CAPACITY] = 0;
}`
Class header for the class person:
`class person{
public:
//stuff
private:
int capacity = 0;
std::string first_name[CAPACITY];
std::string last_name[CAPACITY];
int age[CAPACITY];
//more stuff
}`
C++ is very specific about its naming conventions, so it makes a distinction between capacity and CAPACITY. Because of this, the variable CAPACITY is not defined within the Person.h file.
Also, because CAPACITY is set to a fixed value in your Person.cpp file, whenever you use first_name[CAPACITY], last_name[CAPACITY], or age[CAPACITY] to assign new values, you are only updating the values at the index equal to CAPACITY unless you update the value of CAPACITY itself. In the code you provided, CAPACITY is equal to 20, so your program attempts to update exclusively index 20 with each method call. This will likely cause issues since the person class only attempts to make its arrays on the runtime stack, with a size of 0 each.
Separately, it seems like you want an array of people, but it appears that you are attempting to use a single person object to store the names and ages of multiple people by making these all arrays. Instead, I would recommend making first_name, last_name, and age not arrays, but rather single variables. Then, you can manipulate an array of type person using your CAPACITY variable. You got pretty close, but you can instead declare it as person myPersonArray[CAPACITY] (no need to mention "class" in front of it -- just be sure that you have #include "Person.h" in your main.cpp file). When you want to update a specific person, you can perform an operation like myPersonArray[updateThisIndexNum].update(newFirstName, newLastName, newAge) or some logical equivalent.
As a final note, I almost always highly recommend against using !infile.eof() to control your while loop when reading any file because eof() only indicates whether you have tried to read past the end of an input file. I would highly recommend checking out this post on Stack Overflow where people far more knowledgeable than I explain exactly why this is usually dangerous and how to avoid it.

c++ Not able to add an element in the array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am fairly new to c++. I am trying to add another element in the array. The function should change the array and the number of items in the array after the addEntry function is completed, but it doesn't. If I use the display function to show the array, only the original array is shown. Please help.
#include<iostream>
#include<string>
using namespace std;
const int MAXSIZE = 10; // total size of array
void display(string[], int);
void addEntry(string[], int&);
int main()
{
string name[MAXSIZE] = {"raj","casey","tom","phil"};
int numEntries = 4; // number of elements in the array
string choice; // the user choice to add an element or display or exit
cout<<numEntries<<" names were read in."<<endl;
do
{
cout<<endl<<"Enter menu choice (display, add, quit): ";
getline(cin,choice);
if (choice == "display")
{
display(name, numEntries);
cout<<endl;
}
else if (choice == "add")
{
addEntry(name, numEntries);
cout<<endl;
}
else
{
cout<<"bye"<<endl;
}
} while (choice!="quit");
system ("pause");
return 0;
}
void display(string name[], int numEntries)
{
for (int i = 0; i < numEntries; i++)
{
cout<<name[i]<<endl;
}
return;
}
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE-1)
{
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
getline(cin,name[numEntries]);
numEntries is the number of valid entries in your array. name[numEntries] is the element that is following the last valid entry. Use name[numEntries-1].
Or even better, use std::vector instead of C arrays, after all, you are writing in C++.
Your program works, you are just pointing the the wrong location in your array in addEntry. Remember that arrays in C++ are 0-based, try incrementing the value of numEntries AFTER inserting the element in your array, for example:
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE)
{
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries++]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
The bug in your code is in the following lines:
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
You need to increment numEntries after the call to getline. Use:
cout<<"Enter name of the person to add: ";
if ( getline(cin,name[numEntries]) )
{
// Increment only if getline was successful.
numEntries++;
}

Infinite loop when writing blank records to a binary file

The purpose of the following short program is to search through a binary file (that contains details of different trains) for a particular train (whose number is accepted from the user) and then rewrite a blank record at that location.
That is, I wish to 'delete' that train record.
The problem is that the program goes into an infinite loop and repeatedly writes blank records to the binary file, thereby resulting in an enormous 2 GB .dat file being created.
#include<iostream.h>
#include<fstream.h>
struct train {
int train_no;
char train_name[50], source[20], dest[20];
int n_AC1, n_AC2, n_ACC, n_FC, n_SLC, n_SS; // variables for no of seats
train() { //default constructor
train_no = 0;
n_AC1=0, n_AC2=0, n_ACC=0, n_FC=0, n_SLC=0, n_SS=0;
strcpy(train_name, "/0");
strcpy(source, "/0");
strcpy(dest, "/0");
}
//member functions to accept and display the above values
};
void remove_train(fstream &f) {
train t, blank;
int tno, found = 0;
do {
cout<<"Enter the train no: ";
cin>>tno;
if(tno <=0)
cout<<"Invalid train number. Please re-enter."<<endl;
}
while(tno <=0);
f.seekg(0L, ios::beg);
f.read((char*)&t, sizeof(train));
while(!f.eof() && !found) {
if(t.train_no == tno) {
found = 1;
f.seekp(-sizeof(train), ios::cur);
f.write((char*)&blank, sizeof(train));
cout<<"Train number "<<tno<<" has been deleted!"<<endl;
}
else
f.read((char*)&t, sizeof(train));
}
if(found == 0)
cout<<"ERROR: train not found."<<endl;
}
int main() {
fstream f("Trains.dat", ios::binary | ios::in | ios::out);
remove_train(f);
cin.ignore();
cin.get();
}
When the above program is executed, after I input the train number as '1', the only observable output is "Train number 1 has been deleted", following which the program goes into the aforementioned infinite loop.
This doesn't seem to be an isolated issue; whenever I try to move back by one record and
then write a blank record anywhere in the Railway Reservation project that this code is a part of, the same problem ensues. For instance, if it is a passenger record I wish to overwrite, this is the relevant code fragment that seems to be causing the issue:
f.seekp(-1L*sizeof(passenger), ios::cur);
f.write((char*)&p, sizeof(passenger));
MAJOR EDIT: The problem was fixed when I replaced -sizeof(train) with -110L (which is the byte size of the 'train' structure)! Any idea why this is the case?
I must say I am at a loss to find a fault in your code. I've run a copy of it and it worked as expected.
There are a few minor errors (for instance it will fail if your data file does not exist) and the code could certainly be improved (your usage of f.eof() is somewhat awkward), but nothing that can explain the behaviour you're describing.
Here is the exact version I'm running right now. Except for a bit of extra code to create a dummy data file and a few debug outputs, I don't see any difference with yours.
Maybe you could try to compile it and see if it fails in your environment?
#include<iostream>
#include<fstream>
#include <string.h>
using namespace std;
struct train {
int train_no;
char train_name[50], source[20], dest[20];
int n_AC1, n_AC2, n_ACC, n_FC, n_SLC, n_SS; // variables for no of seats
train() { //default constructor
train_no = 0;
n_AC1=0, n_AC2=0, n_ACC=0, n_FC=0, n_SLC=0, n_SS=0;
strcpy(train_name, "");
strcpy(source, "");
strcpy(dest, "");
}
//member functions to accept and display the above values
};
void remove_train(fstream &f) {
train t, blank;
int tno, found = 0;
do {
cout<<"Enter the train no: ";
cin>>tno;
if(tno <=0)
cout<<"Invalid train number. Please re-enter."<<endl;
}
while(tno <=0);
cout<<"deleting train "<<tno<<endl;
f.seekg(0L, ios::beg);
f.read((char*)&t, sizeof(train));
while(!f.eof() && !found) {
cout<<f.tellp()<<endl;
if(t.train_no == tno) {
found = 1;
f.seekp(-sizeof(train), ios::cur);
cout<<"delete "<<f.tellp()<<"/"<<f.tellg()<<endl;
f.write((char*)&blank, sizeof(train));
cout<<"Train number "<<tno<<" has been deleted!"<<endl;
}
else
{
cout<<"read "<<f.tellg()<<endl;
f.read((char*)&t, sizeof(train));
}
}
if(found == 0)
cout<<"ERROR: train not found."<<endl;
else
cout<<"done"<<endl;
}
void create_trains(int n)
{
fstream f("Trains.dat", ios::binary | ios::out);
train t;
for (int i = 1 ; i <= n ; i++)
{
t.train_no = i;
f.write((char*)&t, sizeof(train));
}
}
int main() {
create_trains (10);
fstream f("Trains.dat", ios::binary | ios::in | ios::out);
remove_train(f);
cin.ignore();
cin.get();
}

Not understanding the error message I'm getting

I doing a freind function program according to this book I have and I did a little of my own code to the program. I puzzle because I get this error message that the "room_num" is undeclared and intellisense identifier "room_num" is undefine. I need help in understanding why this is happen and how to fix it. Here is the code I have been working on for the passed three weeks.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
class HotelRoom
{
friend int Transfer( HotelRoom&, int);
private:
int room_num;
int transroom_num;
int room_cap;
int occup_stat;
double daily_rt;
public:
HotelRoom(int room, int roomcap, int occup, int transroom, double rate = 89.00);
~HotelRoom();
int Display_Number(); //Displays room number and add the method Display_Guest()
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
void Display_Guest();
};
HotelRoom::~HotelRoom()
{
cout << endl<<endl;
cout << "Guest in room "<<room_num << " has checked out." <<endl;
}
int HotelRoom::Display_Number()
{
return room_num;
}
int HotelRoom::Get_Capacity()
{
return room_cap;
}
int HotelRoom::Get_Status()
{
return occup_stat;
}
int HotelRoom::Change_Status(int occup)
{
occup_stat = occup;
if (occup > room_cap)
{
return -1;
}
else
return occup_stat;
}
double HotelRoom::Get_Rate()
{
return daily_rt;
}
double HotelRoom::Change_Rate(double rate)
{
daily_rt = rate;
return daily_rt;
}
int Transfer(HotelRoom& room_r1, int transroom)
{
//if guest transfers to different hotel room, room is vacant and transroom is now occupied
room_r1.room_num = room_r1.transroom_num;
return room_num;
}
int main()
{
cout<< setprecision(2)
<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint);
int room = 0;
int roomcap = 4;
int transroom;
int occup;
double rate = 89.00;
cout<<"\nEnter the room number: "<<endl;
cin>>room;
cout<<"\nEnter the amount of guest to occupy this room: "<<endl;
cin>>occup;
cout<<"\nThe guest has decided to transfer rooms"<<endl;
cout<<"\nEnter the room to transfer the guest to"<<endl;
cin>>transroom;
HotelRoom room1(room,roomcap, occup, transroom, rate ); //initialize the object
if (room1.Change_Status(occup) == -1)
{
cout<<"You have exceeded the room capacity"<<endl;
}
else
{
cout <<"\nThe room number is ";
room1.Display_Number();
cout<<"."<<endl;
cout<<"\nThe name of the primary guest is ";
room1.Display_Guest();
cout <<"."<<endl;
cout<<"\nThe number of guest in the room is "<<room1.Change_Status(occup)<<"." <<endl;
cout<<"\nThe daily rate for room "<<room<< " is "<<room1.Get_Rate()<<"."<<endl<<endl;
cout<<"\nYou have tranferred the guest from room"<<room1.Display_Number()<<"to" <<Transfer(room1,transroom)<<endl;
}
cout<<"\nRoom ";
room1.Display_Number();
cout<<" is vacant."<<endl;
system("PAUSE");
return 0;
}
The function Transfer is not a method of HotelRoom, still you are trying to access room_num in it as if it was. You need to specify which room_num of which HotelRoom instance you mean. Probably you meant return room_r1.room_num instead of return room_num.
Also in your Transfer function you never use the parameter transroom, instead you are using a transroom_num from room_r1. This is probably not what you want.
Finally you haven't implemented the constructor and DisplayRoom of HotelRoom. You should create a stubs, which do nothing or print warnings as long as you haven't implemented the methods properly, so you can at least compile and link the code.
Since you are a beginner I would just stick with member functions and class private variables until you get better at it.
As far as the error message, my guess is that inside the function you are using room_num does not have access to the private parts of the HotelRoom class. Notice I said guess, that's because you should copy and paste the text on the output window here so we can see what exactly is happening.
First, you have to identify that room_num is class member variable.
int Transfer(HotelRoom& room_r1, int transroom)
{
room_r1.room_num = room_r1.transroom_num;
//because room_num is not non class member variable, you have to write like below.
return room_r1.room_num;
//return room_num;
}
Secondly, you did not write definition HotelRoom::HotelRoom(int,int,int,int,double), HotelRoom::Display_Guest(void). So you have to write this constructor and function for avoiding error LNK2019.

wrong answer from boolean function [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
My boolean function check_gift is not working properly.
I copied a txt file into the vector giftstore. Now I want to check if a given item is in the store. To test the function check_gift I took an item from the actual txt file but the function gives the wrong answer. It returns false instead of true.
What am I doing wrong?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <string>
#include <cassert>
using namespace std;
typedef vector<string> Wishes;
int size(Wishes& w){ return static_cast<int>(w.size()); }
struct Wishlist
{
double budget;
Wishes wishes;
};
struct Gift
{
double price;
string name;
};
typedef vector<Gift> Giftstore;
int size(Giftstore& g) { return static_cast<int>(g.size()); }
void read_wishlist_into_struct(ifstream& infile, Wishlist& wishlist)
{
double b;
infile>>b;
wishlist.budget=b;
int i=0;
string name;
getline(infile,name);
while(infile)
{
wishlist.wishes.push_back(name);
i++;
getline(infile,name);
}
infile.close();
}
void show_wishlist(Wishlist wishlist)
{
cout<<"Budget: "<<wishlist.budget<<endl<<endl;
cout<<"Wishes: "<<endl;
for(int i=0; i<size(wishlist.wishes); i++)
{
cout<<wishlist.wishes[i]<<endl;
}
cout<<endl;
}
void read_giftstore_into_vector(ifstream& infile, Gift& gift, Giftstore& giftstore)
{
double p;
string name;
int i=0;
infile>>p;
while(infile)
{
gift.price=p;
getline(infile,name);
gift.name=name;
giftstore.push_back(gift);
i++;
infile>>p;
}
infile.close();
}
void show_giftstore(Giftstore giftstore)
{
cout<<"All possible gifts in giftstore: "<<endl<<endl;
for(int i=0; i<giftstore.size(); i++)
{
cout<<giftstore[i].price<<"\t"<<giftstore[i].name<<endl;
}
cout<<endl;
}
bool check_gift(Giftstore giftstore, string giftname)
{
int i=0;
while(i<size(giftstore))
{
if(giftstore[i].name==giftname)
{
cout<<"Yes"<<endl;
return true;
}
else
{
i++;
}
}
return false;
}
void clear(Wishlist& b)
{
b.budget=0;
while(!b.wishes.empty())
{
b.wishes.pop_back();
}
}
void copy(Wishlist a, Wishlist& b)
{
b.budget=a.budget;
for (int i=0; i<size(b.wishes); i++)
{
b.wishes.push_back(a.wishes[i]);
}
}
int main ()
{
ifstream infile2("giftstore.txt");
Gift gift;
Giftstore giftstore;
read_giftstore_into_vector(infile2, gift, giftstore);
show_giftstore(giftstore);
string giftname;
giftname="dvd Up van Pixar";
bool x;
x=check_gift(giftstore, giftname);
cout<<"in store?: "<<x<<endl;
return 0;
}
Learn how to debug. If you cannot trace line-by-line through your code, then try to keep some kind of log.
For now at least output this to the console.
In your case
1. Verify the input file opened successfully
2. Print out each gift as you read it in.
would be a good way to start.
If you want to be able to put multiple log statements in and then remove them later, you can use a macro which can be turned off in one place.
Logging is a fairly tricky skill to be effective for large projects which continue to run into production, however you should learn how to do it in the short-term to debug your program.
We here cannot even see what is in your input file. This is why people are downvoting your question.
Ok: Now you've told me your issue is you need to trim whitespace from the front of each string you read in.
There are multiple ways to do that but
trimmed = s.substr( s.find_first_not_of(" \n\r\t" ) );
will probably work for now.
However my original answer still holds: please learn to debug. If you'd outputted the strings as you read them in, you would have seen these leading spaces.