C++


C/C++: Syntactic Sugar for If Statement

A standard If Statement in C/C++ can become an one line statement by using the following structure

variable = (STATEMENT)?(RETURN VALUE IF TRUE):(RETURN VALUE IF FALSE)

which is the same as

if (STATEMENT){
  variable = (RETURN VALUE IF TRUE);
}else{
  variable = (RETURN VALUE IF FALSE);
}


C/C++: Capture stdout from a system() command

	FILE *results;
	int queen;
	if (!(results = popen("./precosat -f nqueens.cnf | tail -n +2 | head -n -1 | tr -d v | tr ' ' '\n' | grep -v '^$' | grep ^[0-9]", "r"))) {
		cout << "Unable to Execute Precosat" << endl << "./precosat -f nqueens.cnf | tail -n +2 | head -n -1 | tr -d v | tr ' ' '\n' | grep -v '^$' | grep ^[0-9]" << endl;
		exit(1);
	}
	for (i = 0; i < queens; i++) {
		fscanf(results,"%d",&queen);
		cout << "Queen #" << i+1 << " goes to [" << ((queen%queens)?(queen%queens):queens) << "]" << endl;
	}
	pclose(results);

Above, you will find an example that was used to extract data from the PrecoSAT SAT Solver in order to solve the N-Queens problem. It returns all positive variables, one per line.

You can see that after the call to popen, it creates a pointer to a file stream that can be used as a regular file to read the data from the called process.


Ubuntu: How to compile PrecoSAT v.570 under ubuntu 11.10

By downloading PrecoSAT from http://fmv.jku.at/precosat/ and trying to install it on Ubuntu 11.10 32-bit (Oneiric Ocelot) by:

    • Decompressing the files
    • and calling ./configure && make

I got the following error at make:

g++ -O3 -m32 -static -Wall -Wextra -DNDEBUG -DNLOGPRECO -DNSTATSPRECO  -c precomain.cc
In file included from precomain.cc:23:0:
precosat.hh:164:31: error: ‘ptrdiff_t’ has not been declared
precosat.hh:270:13: error: ‘ptrdiff_t’ has not been declared
make: *** [precomain.o] Error 1

which can be resolved by adding

#include <cstddef>

at the includes in the file precosat.hh


C: How to tell the status of a socket

If you are trying to check if a socket is empty but you cannot use select(), because what you need is to check the write buffers instead of the read ones just to be sure that you have successfully managed to send all data to your peers before terminating, or if you want to tell if a socket buffer is full.

You can use the ioctl to find out.

To check a write buffer if it empty (assuming you have already put data there and want to check if they were consumed):

ioctl(fd, SIOCOUTQ, &pending);

Where fd is the socket’s file descriptor and pending the variable were the remaining size of data will be returned.

To check a read buffer if it empty (assuming someone has already put data there and you want to check if they there is any without consuming them):

ioctl(fd, SIOCINQ, &pending);
*note the difference on the second parameter, where we change the flag from SIOCOUTQ to SIOCINQ

Among other includes be sure to add these:

#include <sys/ioctl.h>
#include <linux/sockios.h>