stoi being printed to console when using std::stoi - c++11

Given a file that contains one integer per line, I am trying to use this code to read the file and store the numbers in a vector.
Strangely, after finishing reading the file, my program is printing the string "stoi". Is this just a behavior of std::stoi? I couldn't find anything about this in documentation.
I am using g++ 6.2.1.
Here is the relevant code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
void usage() {
std::cout << "Usage: ./binary_tree [FILE]\n";
}
int main(int argc, char* argv[]) {
try{
if (argc <= 1) {
usage();
return 1;
}
std::ifstream inputFile;
inputFile.open(argv[1], std::ios::in);
if (!inputFile.is_open()) throw std::runtime_error("Failed to open file");
std::string line;
std::vector<int> nums;
while(!inputFile.eof()) {
getline(inputFile, line);
int num = std::stoi(line);
nums.push_back(num);
}
// Clean up
inputFile.close();
return 0;
}
catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}

Related

boost socket example stuck in while loop

I am trying to learn boost asio socket. there is one interesting example in boost web page which set a deadline time to monitor the timeout and change async io to sync io fashion. but when I remove the deadline timer the program stuck in while loop in write_line, I don't understand why the connection can be setup but the socket write is stuck. it seems that the writing never finished ,the handler never called so the "ec" never changed. Thank you in advance!!
#include <boost/asio/connect.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/system/system_error.hpp>
#include <boost/asio/write.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <boost/bind.hpp>
using boost::asio::deadline_timer;
using boost::asio::ip::tcp;
class client
{
public:
client()
: socket_(io_service_),
deadline_(io_service_)
{
deadline_.expires_from_now(boost::posix_time::seconds(10));
check_deadline(); // without this line which means without the this timer
//async_wait, the code stuck in write_line io_service_.run_one() loop .
}
void connect_handler(const boost::system::error_code& error,boost::system::error_code *er)
{
std::cerr<<"connect handler"<<std::endl;
*er = error;
std::cerr<<error<<std::endl;
}
void connect(const std::string& host, const std::string& service)
{
tcp::resolver::query query(host, service);
tcp::resolver::iterator iter = tcp::resolver(io_service_).resolve(query);
std::cerr<<"connect start"<<std::endl;
boost::system::error_code ec = boost::asio::error::would_block;
boost::asio::async_connect(socket_, iter, bind(&client::connect_handler,this,_1,&ec));
do
{io_service_.run_one();
}while (ec == boost::asio::error::would_block);
std::cerr<<"connect done"<<std::endl; // always works fine!
if (ec || !socket_.is_open())
throw boost::system::system_error(
ec ? ec : boost::asio::error::operation_aborted);
}
void write_handler(const boost::system::error_code& error, std::size_t size,boost::system::error_code* er )
{
std::cerr<<"write handler "<<std::endl;
*er=error;
std::cerr<<error<<std::endl;
}
void write_line(const std::string& line)
{
std::cerr<<"write start"<<std::endl;
std::string data = line + "\n";
boost::system::error_code ec = boost::asio::error::would_block;
boost::asio::async_write(socket_, boost::asio::buffer(data), bind(&client::write_handler,this,_1,_2,&ec));
do
{
io_service_.run_one(); //stuck here without "check_deadline();" in constructor.
}while (ec == boost::asio::error::would_block);
std::cerr<<"write done";
if (ec)
throw boost::system::system_error(ec);
}
private:
void check_deadline()
{
if (deadline_.expires_at() <= deadline_timer::traits_type::now())
{
boost::system::error_code ignored_ec;
socket_.close(ignored_ec);
deadline_.expires_at(boost::posix_time::pos_infin);
throw boost::system::system_error(ignored_ec);
}
deadline_.async_wait(std::bind(&client::check_deadline, this));
}
boost::asio::io_service io_service_;
tcp::socket socket_;
deadline_timer deadline_;
};
int main()
{
try
{
client c,d;
c.connect("216.58.194.164", "80");// google IP.
c.write_line("test");
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
Without comment out line "check_deadline();" in constructor the output is :
connect start
connect handler
system:0
connect done
write start
write handler
system:0
write done
when the line "check_deadline();" comment out in constructor, the output is :
connect start
connect handler
system:0
connect done
write start
and stuck there forever.
The whole point of that particular example is to have timeouts on blocking operations. This is why they use the async_* flavour of functions.
If you don't need that, don't use the async_* flavour at all:
#include <boost/asio.hpp>
#include <iostream>
#include <string>
using boost::asio::ip::tcp;
class client {
public:
client() : socket_(io_service_) { }
void connect(const std::string &host, const std::string &service) {
tcp::resolver::query query(host, service);
socket_.close();
boost::asio::connect(socket_, tcp::resolver(io_service_).resolve(query));
}
std::string read_line() {
boost::system::error_code ec;
boost::asio::read_until(socket_, input_buffer_, '\n', ec);
if (ec == boost::asio::error::eof)
socket_.close();
else if (ec)
throw boost::system::system_error(ec);
std::string line;
std::getline(std::istream(&input_buffer_), line);
return line;
}
void write_line(const std::string &line) {
std::string data = line + "\n";
boost::asio::write(socket_, boost::asio::buffer(data));
}
private:
boost::asio::io_service io_service_;
tcp::socket socket_;
boost::asio::streambuf input_buffer_;
};
int main(int argc, char *argv[]) {
try {
if (argc != 4) {
std::cerr << "Usage: blocking_tcp <host> <port> <message>\n";
return 1;
}
client c;
c.connect(argv[1], argv[2]);
boost::posix_time::ptime time_sent = boost::posix_time::microsec_clock::universal_time();
c.write_line(argv[3]);
for (;;) {
std::string line = c.read_line();
std::cout << "Received '" << line << "'\n";
if (line == argv[3])
break;
}
boost::posix_time::ptime time_received = boost::posix_time::microsec_clock::universal_time();
std::cout << "Round trip time: ";
std::cout << (time_received - time_sent).total_microseconds();
std::cout << " microseconds\n";
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
}
}
That's a lot simpler. In fact, it's too simple in case the packets arriving contain more than 1 line at a time.
Instead of "fixing" the sample by re-complicating it, it can be ENORMOUSLY simpler:
#include <boost/asio.hpp>
#include <iostream>
#include <string>
using boost::asio::ip::tcp;
int main(int argc, char *argv[]) {
try {
if (argc != 4) {
std::cerr << "Usage: blocking_tcp <host> <port> <message>\n";
return 1;
}
tcp::iostream c(argv[1], argv[2]);
boost::posix_time::ptime time_sent = boost::posix_time::microsec_clock::universal_time();
c << argv[3] << "\n";
std::string line;
while (getline(c, line)) {
std::cout << "Received '" << line << "'\n";
if (line == argv[3])
break;
}
boost::posix_time::ptime time_received = boost::posix_time::microsec_clock::universal_time();
std::cout << "Round trip time: ";
std::cout << (time_received - time_sent).total_microseconds();
std::cout << " microseconds\n";
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
}
}

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;
}

Why do I need to set boost::archive::no_codecvt when using textarchive?

We have a class that serialises to boost::archive; but it inserts a 7 character string before the beginning of the archive.
Since upgrading to boost 1.61 from 1.56, this has started failing.
We've found that replacing the line:
boost::archive::polymorphic_text_iarchive ia(ifs);
with
boost::archive::polymorphic_text_iarchive ia(ifs, boost::archive::no_codecvt);
fixes the problem. But it would be nice to know why this has started failing between 1.56 and 1.61, and if this is the correct way to solve the issue.
// boost_archiving.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/exception/exception.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/archive/polymorphic_text_iarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
struct SimpleStruct
{
int x;
int y;
std::string string;
double dub;
template<typename T_ARCHIVE>
void serialize(T_ARCHIVE &a, unsigned int version)
{
a & x;
a & y;
a & string;
a & dub;
}
};
typedef boost::array<char, 7> FileId;
const FileId FILE_ID = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
void writeFile(const std::string& filename)
{
std::ofstream ofs(filename.c_str());
ofs.write(FILE_ID.data(), FILE_ID.size());
boost::archive::text_oarchive oa(ofs);
SimpleStruct simple;
simple.x = 10;
simple.y = 7;
simple.string = "test";
simple.dub = 2.5;
oa << simple;
}
void readFile(const std::string& filename)
{
std::ifstream ifs(filename.c_str());
FileId fileId;
ifs.read(fileId.data(), fileId.size());
if (ifs.good() && (fileId == FILE_ID))
{
boost::archive::polymorphic_text_iarchive ia(ifs); // FAILS on 1.61 Swap this with the line below, or downgrade to boost 1.56
// boost::archive::polymorphic_text_iarchive ia(ifs, boost::archive::no_codecvt);
SimpleStruct simple;
ia >> simple;
std::cout
<< simple.x << " "
<< simple.y << " "
<< simple.string << " "
<< simple.dub << std::endl;
}
}
void main(int argc, char* argv[])
{
try
{
std::string filename("archive.arch");
writeFile(filename);
readFile(filename);
}
catch (const std::exception& e)
{
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
}
}
Sample Archive:
abcdefg22 serialization::archive 11 0 0 10 7 4 test 2.50000000000000000e+000

Reading data with boost asio on client

I am learning boost asio and have mistake. I have written simple client ( I can send data from it but when I read data I cant even compile it) I used protocol buffer to serialize data . So file #include "test.pb.h" is probuffer class
My code client :
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread/thread.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>
#include "test.pb.h"
using boost::asio::ip::tcp;
int main(int argc, char** argv)
{
try
{
// connect to the server:
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
std::string const server_address = "localhost";
std::string const server_port = "10000";
tcp::resolver::query query(server_address, server_port);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
//while ( true)
{
Person p = Person();
p.set_id(22);
p.set_name("Jack vorobey");
// std::cout << p.id();
// std::cout << p.name();
std::string data; // this will hold serialized data
bool ok = p.SerializeToString(&data);
assert(ok);
// std::cout << data.size() << std::endl;
boost::asio::write(socket, boost::asio::buffer(data))
boost::asio::read(socket, boost::asio::buffer(data));;
// break; // Connection closed cleanly by peer.
// std::cout << data.size() << std::endl; // shows a reduction in amount of
remaining data
// boost::asio::read(socket, boost::asio::buffer(data) /*,
}
boost::asio::transfer_exactly(65536) */);
}
catch (std::exception& e)
{
//std::cerr << e.what(luuu) << std::endl;
}
std::cout << "\nClosing";
std::string dummy;
}
The code of my mistake I dont understand :
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const boost::asio::const_buffer' (or there is no acceptable conversion)
1> c:\local\boost_1_55_0\boost\asio\buffer.hpp(136): could be 'boost::asio::mutable_buffer &boost::asio::mutable_buffer::operator =(const boost::asio::mutable_buffer &)'
1> while trying to match the argument list '(boost::asio::mutable_buffer, const boost::asio::const_buffer)'
This is because template<typename Elem, typename Traits, typename Allocator> const_buffers_1 buffer(const std::basic_string<Elem, Traits, Allocator> &) returns an instance of const_buffers_1 (which is a model of ConstBufferSequence concept). Certainly, you cannot read data into a constant buffer.
Do not read data into a std::string, because it's not intended for that (note that its c_str() and data() member functions return const char*). Instead, allocate another buffer or use asio::streambuf.
You can use a streambuf, or specify the (preallocated!) size:
#include <boost/asio.hpp>
#include <string>
using boost::asio::ip::tcp;
int main()
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::socket socket(io_service);
boost::asio::connect(socket, resolver.resolve(tcp::resolver::query("localhost", "10000")));
std::string request("request");
boost::asio::write(socket, boost::asio::buffer(request));
#if 0
std::string response;
response.resize(32);
boost::asio::read(socket, boost::asio::buffer(&response[0], response.size()));
#else
boost::asio::streambuf response;
boost::asio::read(socket, response);
#endif
}

Boost.Asio: What's the Behavior of a deadline_timer with 0 Millisecond Expiration

What the behavior of a deadline_timer whose expiration is 0 milliseconds?
In my code, I have:
boost::asio::io_service ios;
...
boost::asio::deadline_timer ptimer(ios);
ptimer.expires_from_now(boost::posix_time::milliseconds(duration)); // Duration might be 0 sometimes
boost::system::error_code ec;
ptimer.async_wait(boost::bind(&SomeTimeOutHandler, this, ec));
I found that if duration == 0, the handler SomeTimeOutHandler never gets called.
I want it gets called.
However, if I change to duration == 1, the handler does get called.
So what the exact behavior it should be when the deadline_timer's expiration is 0?
Edit:
But the following HelloWorld test program is working (suggested by #Roger):
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
void SomeTimeOutHandler(const boost::system::error_code& ec)
{
if (ec)
{
std::cout << "SomeTimeOutHandler error_code" << std::endl;
}
else
{
std::cout << "I'm in good shape" << std::endl;
}
}
void Test(int duration)
{
boost::asio::io_service ios;
boost::asio::deadline_timer ptimer(ios);
ptimer.expires_from_now(boost::posix_time::milliseconds(duration));
boost::system::error_code ec;
ptimer.async_wait(boost::bind(&SomeTimeOutHandler, ec));
ios.run();
// boost::this_thread::sleep(boost::posix_time::milliseconds(duration * 2 + 1000));
}
int main(int argc, char* argv[])
{
Test(10); // Test(0);
return 0;
}

Resources