this vector has vector probelem is not working - visual-c++

The problem is it prints the full name but not the rest of the lines about the person.
Could someone, please guide me?
I do really appreciate your help!
auto itr = find(my_vec.begin(), my_vec.end(), search );
if(itr != my_vec.end())
{
std::cout << "Match found " << search << std::endl;
std::cout << "\nFull name: " << search << std::endl;
} else {
std::cout << "Match not found "<< std::endl;
}

There are a few style problems with your code:
No need to explicitly initialize strings, they will be empty by default (see here).
Keep a consistent style. For example, either always start brackets in the same line as the function signature or in the next line.
No need to close the file explicitly at the end of the function, this is done when the object goes out of scope (see (destructor) here).
No need to include <map> and <iomanip> headers.
Don't keep unused variables.
Give suggestive names to your variables.
Do not return error codes to the OS when the app is working as it should. Not finding a name is not an error, is it?
It seems your file has 6 entries per contact, so all you have to do is print 5 more lines. You do not need to store the lines in a vector, just parse and print them as you go. Here is an example:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
void findContact(std::string fullName, std::string contactListPath) {
std::ifstream inFile{contactListPath};
if (!inFile) {
std::cerr << "File could not be open!" << std::endl;
return;
}
std::string line;
while (std::getline(inFile, line)) {
if (line == fullName) {
std::cout << "Match found: \n";
std::cout << "\nFull name: " << fullName;
std::cout << "\nAddress: " << (std::getline(inFile, line), line);
std::cout << "\nE-mail: " << (std::getline(inFile, line), line);
std::cout << "\nPhone: " << (std::getline(inFile, line), line);
std::cout << "\nBirthday: " << (std::getline(inFile, line), line);
std::cout << "\nNote: " << (std::getline(inFile, line), line) << std::endl;
return;
}
}
std::cout << "Match not found " << std::endl;
}
int main() {
std::string fullName;
std::string contactListPath;
std::cout << "Enter full name to search: ";
std::getline(std::cin, fullName);
std::cout << "Enter path to contact list: ";
std::getline(std::cin, contactListPath);
findContact(fullName, contactListPath);
return 0;
}

If every entry contains 6 lines. Then you can print all the lines starting from the line that you found like:
auto itr = find(my_vec.begin(), my_vec.end(), search );
if(itr != my_vec.end())
{
std::cout << "Match found " << std::endl;
// print the next 6 lines
for(int remaining = 6;remaining > 0 && itr!=my_vec.end(); itr++,remaining--) {
std::cout << *itr << std::endl;
}
} else {
std::cout << "Match not found "<< std::endl;
}

Related

why the "getline" command does not get recognized by VS?

The word "getline" is a red and underlined, which indicate an error:
#include <iostream>
using namespace std;
string ReadName()
{
string Name;
cout << "Please Enter Your Name: " << endl;
getline(cin, Name);
return Name;
}
void PrintName(string Name)
{
cout << "\nYour name is " << Name << endl;
}
int main()
{
PrintName(ReadName());
return 0;
}
The VS Gives an error regarding getline

std array too few template arguments

When runnig my project i see these problems. Does anyone know the solution?
'std array': too few template arguments.
cannot use this indirection on type 'std::array'.
too few arguments for class template "std::array".
I tried to remove using namespace std; into std::array or cli::array but it didn't helped a lot
#include "pch.h"
#include "windows.h"
#include <iostream>
#include <string>
using namespace System;
using namespace std;
class Dog
{
public:
Dog();
Dog(int initAge);
~Dog();
int GetAge();
void SetAge(int Age);
void GawGaw(string S);
private: int itsAge;
};
Dog::Dog()
{ }
Dog::Dog(int initAge)
{
itsAge = initAge;
}
Dog::~Dog()
{ }
int Dog::GetAge()
{ return itsAge;
}
void Dog::SetAge(int Age)
{ itsAge = Age;
}
void Dog::GawGaw(string S)
{ cout << S + " -> GawGaw \n";
}
int main(array<System::String ^> ^args)
{
cout << "\n My Favorite dogs \n";
Dog Bob;
cout << "\nBob is a dog who is ";
cout << Bob.GetAge() << " years old. \n";
Bob.SetAge(7);
cout << "No. Bob is a dog who is ";
cout << Bob.GetAge() << " years old. \n";
Bob.GawGaw("Bob");
Dog* Fox = new Dog(10);
cout << "\nFox is a dog who is ";
cout << Fox->GetAge() << " years old. \n";
Fox->SetAge(12);
cout << "No. Fox is a dog who is ";
cout << Fox->GetAge() << " years old. \n";
Fox->GawGaw("Fox");
Dog Rex(5);
cout << "\nRex is a dog who is ";
cout << Rex.GetAge() << " years old. \n";
Rex.SetAge(8);
cout << "No. Rex is a dog who is ";
cout << Rex.GetAge() << " years old. \n";
Rex.GawGaw("Rex");
Console::ReadLine();
return 0;
}

Consumer doesn't see state of variable changing

In the complete code (see below), at some point (after N iterations) the consumer (function executionServiceHandler while (inService_) is entered, despite inService_ having been changed (in the same thread) [or so it seems from log output].
I have as far as possible tried to guard std::cout as well, although I'm not sure this is necessary.
Could you perhaps crit the code. I know strictly speaking I don't need to use StopServiceCmd to let the thread complete, but in my mind I can't see why it shouldn't work.
Also, I could have used std::function, but the example is simplified from original.
I could add that I tested this on GCC (latest), after the original example failed on VCC (2017)
Code follows (EDIT - now using std::function:
#include <thread>
#include <functional>
#include <mutex>
#include <iostream>
#include <queue>
#include <sstream>
#include <condition_variable>
class ThreadCmdConsumer
{
public:
using Guard = std::lock_guard<std::mutex>;
using UniqueLock = std::unique_lock<std::mutex>;
ThreadCmdConsumer()
: inService_(),
executionServiceThread_(std::bind(&ThreadCmdConsumer::executionServiceHandler, this))
{
//Wait while thread does not exist...
UniqueLock lock(cmdQMutex_);
while (!inService_) {
conditional_.wait(lock);
}
std::cout << std::hex << this << " constructed and consumer waiting..." << std::endl;
}
~ThreadCmdConsumer() {
static std::size_t nth = 0;
{
UniqueLock lock(cmdQMutex_);
std::cout << "destructing (" << std::dec << nth++ << "): " << std::hex << this << std::endl;
}
process([this](){
//Note: inService_ can only be changed in consumer thread...
inService_ = false;
std::cout << "consumer_->inService state: " << inService_ << std::endl;
});
UniqueLock lock(cmdQMutex_);
std::cout << "producer " << std::hex << this << " destructor has lock" << std::endl;
while (inService_) {
std::cout << "producer " << std::hex << this << " destructor in service, entering wait" << std::endl;
conditional_.wait(lock);
std::cout << "producer " << std::hex << this << " destructor exited wait - has lock" << std::endl;
}
// Join will always succeed as result of StopServiceCmd that sets inService to false
// (in its own thread context). Once join completes, we are certain of executionServiceHandler
// exiting normally.
std::cout << "produces " << std::hex << this << " destructor joining" << std::endl;
lock.unlock();
try {
executionServiceThread_.join();
}
catch (const std::system_error& ex) {
UniqueLock lock(cmdQMutex_);//for cout
std::cout << "Exception during join" << ex.what() << std::endl;
abort();
}
}
void executionServiceHandler()
{
{ //Starts the service...
UniqueLock lock(cmdQMutex_);
inService_ = true;
lock.unlock();
conditional_.notify_one();
}
try {
UniqueLock lock(cmdQMutex_);
while (inService_) {
std::cout << "consumer " << std::hex << this << " has lock" << std::endl;
// Catering for spurious wake-ups too, hence while...
while (cmdQ_.empty()) {
std::cout << "consumer " << std::hex << this << " waiting" << std::endl;
conditional_.wait(lock);
std::cout << "consumer " << std::hex << this << " woken" << std::endl;
}
//Now we have the lock, and queue most certainly not empty
auto cmd = std::move(cmdQ_.front());
cmdQ_.pop();
//###lock.unlock(); // Don't want to be locked while executing... removed conservatively
(cmd)();
}
std::cout << "consumer " << std::hex << this << " execution complete" << std::endl;
}
catch(const std::exception& ex) {
std::cerr << "Unexpected " << ex.what() << std::endl;
abort();
}
//Not in service - notify when we've left (then we can truly join...)
conditional_.notify_one();
}
void process(std::function<void()>&& cmd)
{
UniqueLock lock(cmdQMutex_);
std::cout << "producer " << std::hex << this << " has lock" << std::endl;
bool notificationRequired = cmdQ_.empty();
cmdQ_.push(move(cmd));
if (notificationRequired) {
std::cout << "producer " << std::hex << this << " notifying" << std::endl;
lock.unlock();
conditional_.notify_one();
}
else {
std::cout << "producer " << std::hex << this << " not notifying" << std::endl;
}
}
private:
bool inService_;
std::queue<std::function<void()>> cmdQ_;
std::condition_variable conditional_;
std::mutex cmdQMutex_;
std::thread executionServiceThread_;
};
typedef std::function<void(const std::string&)> Handler;
struct ThreadOwner
{
ThreadCmdConsumer executor_;
// Do it done in the context of executor....
void doIt(const Handler& handler)
{ }
};
int main()
{
std::cout << "Program started" << std::endl;
//Sometimes deadlocks on thread being killed
for (int i = 0; i < 1000; ++i) {
auto handler = [](const std::string&){};
{
ThreadOwner owner;
owner.executor_.process([&handler, &owner]() {
owner.doIt(handler);
});
}
}
}

Can't find the error

This program is a nightmare, it wont even give me errors when ran, visual studios tells me nothing and i need some help
#include <iostream>
using namespace std;
class Textbook
{
private:
char *aPtr;
char *tPtr;
int yearPub;
int numPages;
char bookType;
public:
Textbook(char *, char *, int, int, char);
void display();
void operator=(Textbook&);
};
Textbook::Textbook(char*string = NULL, char*string2 = NULL, int ypub = 0, int npages = 0, char btype = 'X')
{
aPtr = new char[strlen(string) +1];
strcpy(aPtr, string);
tPtr = new char[strlen(string2) +1];
strcpy(tPtr, string2);
yearPub = ypub;
numPages = npages;
bookType = btype;
}
void Textbook::display()
{
cout << "The name of the author is: " << *aPtr << endl;
cout << "The Title of the book is: " << *tPtr << endl;
cout << "The year it was published is: " << yearPub << endl;
cout << "The number of pages is: " << numPages << endl;
cout << "The initial of the title is: " << bookType << endl;
return;
}
void Textbook::operator=(Textbook& newbook)
{
if(aPtr != NULL) //check that it exists
delete(aPtr);// delete if neccessary
aPtr = new char[strlen(newbook.aPtr) + 1];
strcpy(aPtr, newbook.aPtr);
if(tPtr != NULL) //check that it exists
delete(tPtr); // delete if neccessary
tPtr = new char[strlen(newbook.tPtr) + 1];
strcpy(tPtr, newbook.tPtr);
yearPub = newbook.yearPub;
numPages = newbook.numPages;
bookType = newbook.bookType;
}
void main()
{
Textbook book1("sehwag", "Programming Methods", 2009, 200, 'H');
Textbook book2("Ashwin", "Security Implementation", 2011, 437, 'P');
Textbook book3;
book1.display();
book2.display();
book3.display();
book3 = book1;
book2 = book3;
book1.display();
book2.display();
book3.display();
}
im not sure if the problem lies in the default constructor but that's about the only thing i could think of, but im not sure at all on how to fix it.
Problem is with the default-parameters in the constructor.
You can't do those kind of operations with NULL-pointers.
Textbook book3;
crashes your program.
Change:
cout << "The name of the author is: " << *aPtr << endl;
cout << "The Title of the book is: " << *tPtr << endl;
to:
cout << "The name of the author is: " << aPtr << endl;
cout << "The Title of the book is: " << tPtr << endl;
Also change:
aPtr = new char[strlen(string) +1];
strcpy(aPtr, string);
to:
if (string != NULL)
{
aPtr = new char[strlen(string) +1];
strcpy(aPtr, string);
}
else
{
aPtr = new char[1];
aPtr[0] = '\0';
}
and ditto for tptr and string2.
The reason you need this checking is because you have NULL as a default value for your two string inputs, so when you call the constructor with no arguments (as is the case with book3) these strings are just NULL pointers. Calling functions such as strlen or strcat with a NULL pointer will result in an exception as you have seen.
Ideally you should not be using C-style strings with C++ - use C++ strings instead - this will help to avoid problems such as the above.

How do I copy files and folders using boost and Visual Studio 2005?

I'm trying to use boost::filesystem to copy files and folders (just like a standard copy a folder and paste it in windows explorer).
Although I've been to the boost::filesystem documentation, I still don't really know how to go about doing this.
Do you have to recursively go though each directory (creating it) and find each file copying it?
Additionally, how do you copy the file in C++/Boost?
P.S. I'm using Boost 1.40.0
Update
I think I may have ended up creating an answer to this one, only concern being that I don't do any try-catch errors to check for locked files and folders.
The following code makes a copy of a directory in the relative path "../example/ecomm" and duplicates it to a non-existing path "../example/dup_ecomm":
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/regex.hpp>
#include <iostream>
#include <fstream>
#include<string>
bool copy_dir( const boost::filesystem::path & ext_dir_path, // the existing directory
const boost::filesystem::path & duplicate_dir_path // the duplicate directory
)
{
std::cout << "BEGIN: copy_dir " << endl;
std::cout << "- ext_dir_path: " << ext_dir_path << endl;
std::cout << "- duplicate_dir_path: " << duplicate_dir_path << endl;
// 1. Ensure that the directory we are trying to copy exists.
if (!boost::filesystem::exists( ext_dir_path ) ) return false;
bool createdDir = boost::filesystem::create_directory( duplicate_dir_path );
// cout << "createdDir: " << createdDir << endl;
copy_dir(ext_dir_path, // the existing directory
duplicate_dir_path, // the duplicate directory,
ext_dir_path, // the base path for the existing directory
duplicate_dir_path,
true);
std::cout << "END: copy_dir " << endl;
}
bool copy_dir( const boost::filesystem::path & ext_dir_path, // the existing directory
const boost::filesystem::path & duplicate_dir_path, // the duplicate directory,
const boost::filesystem::path & base_ext_dir_path, // the base path for the existing directory
const boost::filesystem::path & base_duplicate_dir_path, // the base path for the duplicate of the exisiting directory
bool isRootPath)
{
// Debug input arguments
std::cout << "BEGIN: copy_dir " << endl;
std::cout << "- ext_dir_path: " << ext_dir_path << endl;
std::cout << "- duplicate_dir_path: " << duplicate_dir_path << endl;
std::cout << "- base_ext_dir_path: " << base_ext_dir_path << endl;
std::cout << "- base_duplicate_dir_path: " << base_duplicate_dir_path << endl;
std::cout << "- isRootPath: " << isRootPath << endl;
boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
cout << "--Beginning itr loop" << endl;
for ( boost::filesystem::directory_iterator itr( ext_dir_path );
itr != end_itr;
++itr )
{
if ( boost::filesystem::is_directory(itr->status()) )
{
cout << "---itr->path(): " << itr->path() << endl;
boost::filesystem::path newExtDir(itr->path());
string dup_path = itr->path().string();
boost::algorithm::replace_first(dup_path, base_ext_dir_path.string(), base_duplicate_dir_path.string());
cout << "dup_path: " << dup_path << endl;
boost::filesystem::path new_dup_dir(dup_path);
bool createdDir = boost::filesystem::create_directory( new_dup_dir );
cout << "creating directory " << dup_path << " created: " << createdDir << endl;
boost::filesystem::path newDuplicateDir(duplicate_dir_path);
copy_dir(newExtDir, // the existing directory
newDuplicateDir, // the duplicate directory,
base_ext_dir_path,
base_duplicate_dir_path,
false);
}
else
{
cout << "---isLeaf: " << itr->path() << endl;
string dup_path = itr->path().string();
boost::algorithm::replace_first(dup_path, base_ext_dir_path.string(), base_duplicate_dir_path.string());
string src_path = itr->path().string();
cout << "src_path: " << src_path << endl;
cout << "dup_path: " << dup_path << endl;
boost::filesystem::path s_path(src_path);
boost::filesystem::path d_path(dup_path);
boost::filesystem::copy_file(s_path, d_path);
}
}
std::cout << "--Ending itr loop" << endl;
std::cout << "END: copy_dir " << endl;
return false;
}
test_suite*
init_unit_test_suite( int, char* [] ) {
boost::filesystem::path ext_dir("..\\example\\ecomm");
boost::filesystem::path dir_dup("..\\example\\dup_ecomm");
copy_dir(ext_dir,
dir_dup); // the duplicate directory,
// ... unit tests...etc...
}
My question now is what I'm I forgetting to do in regards to locked files and directories?
boost::filesystem::recursive_directory_iterator

Resources