expected ‘,’ or ‘...’ before ‘&&’ token while cmake, but not while pure g++ compilation [duplicate] - g++

This question already has answers here:
How do I activate C++ 11 in CMake?
(17 answers)
Closed 4 years ago.
i am just found for myself "cmake". And now trying to implement it to my few old programs. But now, i encounter this error while compiling with cmake:
cd project directory
cmake.
make - and here error is thrown "expected ‘,’ or ‘...’ before ‘&&’ token, TString(TString &&_obj);"
But, if i compile this program with:
g++ program.cpp -o program -std=c++11 - it compiles correctly without errors.
I am on Ubuntu(gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.10)
I don't clearly understand what's wrong.
Here is my code:
string.cpp
#include <iostream>
#include <string>
#include <cstring>
#include "TString.h"
using namespace std;
int main(int argc, char const *argv[]) {
long n;
std::cout << "\n Enter num to initialize binstring" << '\n';
std::cin >> n;
TBinString bin(n);
std::cout << "\n Your number in bin" << '\n';
TBinString bin2(bin);
std::cout << bin2.GetString() << '\n';
bin2 ="101";
std::cout << "\nAdding 5 to your number" << '\n';
bin += bin2;
std::cout << bin.GetString() << '\n';
system("pause");
return 0;
}
TString.h
#include <iostream>
#include <cstring>
class TString {
protected:
char *str;
int size;
inline void eat_rest();
public:
TString();
TString(int);
TString(const char*);
TString(TString &_obj);
TString(TString &&_obj);
~TString();
void Set(const char*);
const char* GetString() const;
int GetSize() const;
int Len();
void Clear();
void operator=(const TString &_obj);
void operator+=(const TString &_obj);
void operator+=(const char*);
TString operator+(const TString &_obj);
TString operator+(const char*);
friend bool operator == (const TString &_left, const TString &_right);
friend bool operator != (const TString &_left, const TString &_right);
};
class TBinString : public TString{
public:
TBinString();
TBinString(long);
TBinString(const char*);
TBinString(TBinString &);
TBinString(TBinString &&);
~TBinString();
void Sign();
int FindBits(long);
TBinString Sum(const char*);
void operator=(const TBinString &_obj);
TBinString operator+(TBinString &);
TBinString operator+(const char*);
TBinString operator+(const long);
void operator+=(const TString &);
void operator+=(const char*);
void operator+=(const long);
};
TString.cpp
#include "TString.h"
TString::TString(int n){
this->str = new char[n];
this->size = n;
}
TString::TString():TString(80){}
TString::TString(const char* str):TString(strlen(str)+1){
//strncpy(this->str, str, this->size);
strcpy_s(this->str, this->size, str);
}
TString::TString(TString &_obj):TString(_obj.size){
//strncpy(this->str, _obj.str, this->size);
strcpy_s(this->str, this->size, _obj.str);
}
TString::TString(TString &&_obj){
this->str = _obj.str;
_obj.str = NULL;
this->size = _obj.size;
_obj.size = 0;
}
TString::~TString(){
delete [] str;
}
void TString::Set(const char *_str){
delete [] this->str;
this->str = new char[strlen(_str)+1];
this->size = strlen(_str)+1;
//strncpy(this->str, _str, this->size);
strcpy_s(this->str, this->size, _str);
}
const char* TString::GetString() const{
if (this->str == NULL) {
return "<string is empty>";
}
return this->str;
}
int TString::GetSize() const{
return this->size;
}
int TString::Len(){
return strlen(this->str);
}
void TString::Clear(){
this->Set("");
}
void TString::operator=(const TString &_obj){
this->Set(_obj.str);
}
TString TString::operator+(const TString &_obj){
char *buff = new char[strlen(this->str) + strlen(_obj.str) + 1];
size_t size = strlen(this->str) + strlen(_obj.str) + 1;
buff[0] = 0;
//strncat(buff, this->str, size);
strcat_s(buff, size, this->str);
//strncat(buff, _obj.str, size);
strcat_s(buff, size, _obj.str);
TString ret(buff);
return ret;
}
TString TString::operator+(const char *_obj){
char *buff = new char[strlen(this->str) + strlen(_obj) + 1];
size_t size = strlen(this->str) + strlen(_obj) + 1;
buff[0] = 0;
//strncat(buff, this->str, size);
strcat_s(buff, size, this->str);
//strncat(buff, _obj.str, size);
strcat_s(buff, size, _obj);
TString ret(buff);
return ret;
}
void TString::operator+=(const TString &_obj){
*this = *this + _obj;
}
void TString::operator+=(const char *_obj){
*this = *this + _obj;
}
bool operator == (const TString &_left, const TString &_right){
if (_left.GetSize() == _right.GetSize()) {
for (size_t i = 0; i < _left.GetSize(); i++) {
if (_left.GetString()[i] != _right.GetString()[i])
return false;
}
return true;
}else
return false;
}
bool operator!=(const TString &_left, const TString &_right){
return !(_left == _right);
}
void TString::eat_rest(){
while (std::cin.get() != '\n') ;
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// class TBinString
TBinString::TBinString(){
this->str = NULL;
this->size = 0;
}
TBinString::TBinString(long n):TBinString(){
this->size = this->FindBits(n) +2; //one for sign and one fo \0
this->str = new char[this->size];
this->str[0] = '0';
long m = abs(n);
for (size_t i = this->size-2; i > 0; i--) {
this->str[i] = (m % 2) + '0';
m /= 2;
}
this->str[this->size-1] = '\0';
if (n < 0)
this->Sign();//доп. код
}
TBinString::TBinString(const char* _str):TBinString(){
for (size_t i = 0; i < strlen(_str); i++) {
if (_str[i] != '1' && _str[i] != '0') {
this->str = NULL;
this->size = 0; //one for \0
return;
}
}
this->size = strlen(_str) +1; //one for \0
this->str = new char[this->size];
//strncpy(this->str, _str, this->size);
strcpy_s(this->str, this->size, _str);
}
TBinString::TBinString(TBinString &_obj):TBinString(){
this->size = _obj.size; //one for \0
this->str = new char[this->size];
//strncpy(this->str, _obj.str, this->size);
strcpy_s(this->str, this->size, _obj.str);
}
TBinString::TBinString(TBinString &&_obj):TBinString(){
this->size = _obj.size; //one for \0
this->str = _obj.str;
_obj.str = NULL;
}
TBinString::~TBinString(){}
int TBinString::FindBits(long n){
int ret = 0;
n = abs(n);
while (n > 0) {
n = n /2; ret++;
}
return ret;
}
void TBinString::Sign(){
this->str[0] = '1';
//inverting
for (size_t i = this->size-2; i > 0; i--) {
if (this->str[i] == '0')
this->str[i] = '1';
else
this->str[i] = '0';
}
//adding 1
for (size_t i = this->size-2; i > 0; i--) {
if (this->str[i] == '0'){
this->str[i] = '1';
break;
}
else
this->str[i] = '0';
}
}
TBinString TBinString::Sum(const char *_str){
bool over = false;
int size_left = this->size;
int size_right = strlen(_str)+1;
TBinString buff;
buff.size = size_left > size_right ? size_left : size_right;
size_left -= 2; size_right -= 2;
int i = buff.size-2;
buff.str = new char[buff.size];
for (;size_left >= 0 && size_right >= 0; i--, size_left--, size_right--) {
if (this->str[size_left] == '1') {
if (_str[size_right] == '0'){
if (over)
buff.str[i] = '0';
else
buff.str[i] = '1';
}
else{//_str[size_right] == '1'
if (over)
buff.str[i] = '1';
else{
buff.str[i] = '0';
over = true;
}
}
}else{//this->str[size_left] == '0'
if (_str[size_right] == '0') {
if (over) {
buff.str[i] = '1';
over = false;
}
else
buff.str[i] = '0';
}else{//_str[size_right] == '1'
if (over)
buff.str[i] = '0';
else
buff.str[i] = '1';
}
}
}
while (size_left >= 0) {
if (this->str[size_left] == '1') {
if (over)
buff.str[i] = '0';
else
buff.str[i] = '1';
}else{//this->str[size_left] == '0'
if (over) {
buff.str[i] = '1';
over = false;
}else
buff.str[i] = '0';
}
size_left--; i--;
}
while (size_right >= 0) {
if (_str[size_right] == '1') {
if (over)
buff.str[i] = '0';
else
buff.str[i] = '1';
}else{//_str[size_right] == '0'
if (over) {
buff.str[i] = '1';
over = false;
}else
buff.str[i] = '0';
}
size_right--; i--;
}
buff.str[buff.size-1] = '\0';
return buff;
}
void TBinString::operator=(const TBinString &_obj){
this->Set(_obj.str);
}
TBinString TBinString::operator+(TBinString &_obj){
return this->Sum(_obj.GetString());
}
TBinString TBinString::operator+(const char *_str){
return this->Sum(_str);
}
TBinString TBinString::operator+(const long _var){
TBinString tmp(_var);
return this->Sum(tmp.GetString());
}
void TBinString::operator+=(const TString &_obj){
*this = this->Sum(_obj.GetString());
}
void TBinString::operator+=(const char *_str){
*this = this->Sum(_str);
}
void TBinString::operator+=(const long _var){
TBinString tmp(_var);
*this = this->Sum(tmp.GetString());
}

Got it, when writing question. Sorry for that!
You need to add standart c++11 flag when compiling with cmake

Related

Connection between two Indy UDP Servers

I'm using RAD Studio 10.2 with two instances of TIdUDPServer from Indy 10.
I run my program on Windows 10 and check the counters of sent and received packages, but there are no packages received. At the same time, I see through Wireshark that they come to the PC, but the second TIdUDPServer does not receive the packages. Why?
Here is my code:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
typedef struct {
char Data[10000];
} struct_Buffer;
int i = 0;
int n = 0;
int k = 0;
int TxSize = 1400;
char TxData;
struct_Buffer TxBuffer;
AnsiString ServerIP1 = "192.168.10.1";
AnsiString ServerIP2 = "192.168.10.2";
TBytes Buffer;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
class TMyQueueProc1 : public TCppInterfacedObject<TThreadProcedure>
{
private:
int m_counter;
TIdBytes m_bytes;
public:
TMyQueueProc1(int ACounter, const TIdBytes &AData) : m_counter(ACounter), m_bytes(AData) {}
INTFOBJECT_IMPL_IUNKNOWN(TInterfacedObject);
void __fastcall Invoke()
{
Form1->Label1->Caption = "Rx " + IntToStr(m_counter);
}
};
void __fastcall TForm1::FormCreate(TObject *Sender)
{
try {
TIdSocketHandle *SocketHandle_Server = Form1->IdUDPServer1->Bindings->Add();
SocketHandle_Server->IP = ServerIP1;
SocketHandle_Server->Port = 4004;
Form1->IdUDPServer1->Active = true;
}
catch(Exception *ex) {
ShowMessage("IdUDPServer1 start error!");
}
try {
TIdSocketHandle *SocketHandle_Echo = Form1->IdUDPServer2->Bindings->Add();
SocketHandle_Echo->IP = ServerIP2;
SocketHandle_Echo->Port = 4004;
Form1->IdUDPServer2->Active = true;
}
catch(Exception *ex) {
ShowMessage("IdUDPServer2 start error!");
}
Timer1->Interval = 100;
Timer1->Enabled = true;
Label3->Caption = "IdUPDServer1: " + ServerIP1;
Label4->Caption = "IdUDPServer2: " + ServerIP2;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
TxData++;
if (TxData == 255) TxData = 0;
for (k = 0; k < TxSize; k++) TxBuffer.Data[k] = TxData;
Buffer = RawToBytes(&TxBuffer.Data[0], TxSize);
Form1->IdUDPServer1->SendBuffer(ServerIP2, 4004, Buffer);
n++;
Label2->Caption = "Tx " + IntToStr(n);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::IdUDPServer2UDPRead(TIdUDPListenerThread *AThread, const TIdBytes AData,
TIdSocketHandle *ABinding)
{
i++;
TThread::Queue(NULL, _di_TThreadProcedure(new TMyQueueProc1(i, AData)));
}
//---------------------------------------------------------------------------

C/C++ Socket UDP Client Data Sending -> Keep sending only one peer

i faced a problem with Multi-UDP Socket.
Now I have a PC(192.168.58.200), and 3 MPU(STM32F4)(192.168.85.100~102).
and I Conncected RS232 With MPU.
When MPU got a messasge, it returns just 'X', and print out same thing with RS232, so i can distinguish when PC can not send message and when MPU can get a message but PC can not recieve the message.
below is my code, Especially "UdpClient[c].Write( TempStr, strlen(TempStr));" doesnt work.
when it send mesage, only one MPU can get a message, and keep reciving 30~40 sec, some times changed other MPU.
1:1 is fine, but problem is more 2 Peer. please share your experiences.
// udpclient.cpp
#include <stdio.h>
#include "UDPCLIENT.h"
#include "UDPServer.h"
struct sPeer
{
char IP[64];
int Port;
};
#define CUR_MPU 3
#define MAX_MPU 16
sPeer Peer[MAX_MPU];
unsigned long _stdcall ReadThread(void *Param)
{
UDPSERVERSOCKET UDPSocket;
int ID = (int)Param;
printf("Server ID %d\n", ID);
UDPSocket.Open(Peer[ID].Port);
while (1)
{
char ReadBuffer[1024];
char Addr[32];
UDPSocket.Read(Addr, ReadBuffer, 1024);
printf("%s>%s\n", Addr, ReadBuffer);
}
UDPSocket.Close();
return 0;
}
int main()
{
sprintf(Peer[0].IP, "192.168.58.100"); Peer[0].Port = 7726;
sprintf(Peer[1].IP, "192.168.58.101"); Peer[1].Port = 7727;
sprintf(Peer[2].IP, "192.168.58.102"); Peer[2].Port = 7728;
///////////////////////쓰레드를 연다./////////////////
for (int c = 0; c < CUR_MPU; c++)
{
DWORD ID;
HANDLE thread01 = CreateThread( NULL,//보안 속성
0,//스택의 크기
ReadThread,//함수
(void *)c,//인자
0,//생성플러그
&ID);// 아이디
}
UDPCLIENTSOCKET UdpClient[CUR_MPU];
for (int c = 0; c < CUR_MPU; c++)
{
UdpClient[c].Open(Peer[c].IP, Peer[c].Port);
}
while (1)
{
char TempStr[1024];
printf("보낼 메시지 ---");
scanf("%s", TempStr);
for (int c = 0; c < CUR_MPU; c++)
{
UdpClient[c].Write( TempStr, strlen(TempStr));
}
}
for (int c = 0; c < CUR_MPU; c++)
UdpClient[c].Close();
return 0;
}
Cleint.cpp
#include "UDPCLIENT.h"
int UDPCLIENTSOCKET::Open(char *Address , int Port)
{
unsigned int addr;
int nRtn = WSAStartup(MAKEWORD(1, 1), &wsaData);
if (nRtn != 0) {
perror("WSAStartup 오류\n");
return -1;
}
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("소켓 오류\n");
WSACleanup();
return -2;
}
lpHostEnt = gethostbyname(Address);
if (lpHostEnt == NULL) {
addr = inet_addr(Address);
lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL) {
perror("서버를 찾을 수 없습니다.\n");
_getch();
return -3;
}
}
memset(&addrin, 0, sizeof(addrin));
memcpy(&(addrin.sin_addr),
lpHostEnt->h_addr_list[0],
lpHostEnt->h_length);
addrin.sin_port = htons(Port);
addrin.sin_family = AF_INET;
//addrin.sin_addr.s_addr =
// *((unsigned long *)lpHostEnt->h_addr);
return 1;
}
void UDPCLIENTSOCKET::Close()
{
closesocket(s);
WSACleanup();
}
int UDPCLIENTSOCKET::Write(char *Address, int Port, char *Buffer, int Size)
{
unsigned int addr;
lpHostEnt = gethostbyname(Address);
if (lpHostEnt == NULL) {
addr = inet_addr(Address);
lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL) {
perror("서버를 찾을 수 없습니다.\n");
_getch();
return -3;
}
}
memset(&addrin, 0, sizeof(addrin));
memcpy(&(addrin.sin_addr),
lpHostEnt->h_addr_list[0],
lpHostEnt->h_length);
addrin.sin_port = htons(Port);
addrin.sin_family = AF_INET;
int nRtn = sendto(s, Buffer, Size, 0,
(LPSOCKADDR)&addrin, sizeof(addrin));
return nRtn;
}
int UDPCLIENTSOCKET::Write(char *Buffer, int Size)
{
int nRtn = sendto(s, Buffer, Size, 0,
(LPSOCKADDR)&addrin, sizeof(addrin));
return nRtn;
}
Server.cpp
#include "UDPServer.h"
int UDPSERVERSOCKET::Open(u_short uport)
{
int nRtn;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
perror("WSAStartup Error\n");
return -1;
}
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("socket 오류\n");
WSACleanup();
return -2;
}
memset(&addrin, 0, sizeof(addrin));
addrin.sin_port = htons(uport);
addrin.sin_family = AF_INET;
addrin.sin_addr.s_addr = htonl(INADDR_ANY);
nRtn = bind(s, (LPSOCKADDR)&addrin, (int)sizeof(addrin));
if (nRtn == SOCKET_ERROR) {
perror("bind 오류\n");
closesocket(s);
WSACleanup();
return -3;
}
return 1;
}
int UDPSERVERSOCKET::Read(char *Addr, char *Buffer, int Length)
{
int fromlen = (int)sizeof(from);
int nRtn = recvfrom(s,
Buffer,
Length -1,
0,
(SOCKADDR *)&from,
&fromlen);
if (nRtn == SOCKET_ERROR)
{
Addr[0] = 0;
perror("recvform 오류\n");
closesocket(s);
WSACleanup();
return -4;
}
strcpy(Addr, inet_ntoa(from.sin_addr));
Buffer[nRtn] = '\0';
return 1;
}
int UDPSERVERSOCKET::Close()
{
closesocket(s);
WSACleanup();
printf("WSACleanup 완료\n");
return 1;
}
void UDPSERVERSOCKET::ShowErrorMessage(int i)
{
}
void UDPSERVERSOCKET::ReturnClientIP(char *Buffer)
{
}

How to change this app to disable input from command line?

This is the Original code:
#include <stdio.h>
#include <string.h>
#include <assert.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <windows.h>
#else
#include <sys/select.h>
#endif
#include <sphinxbase/err.h>
#include <sphinxbase/ad.h>
#include "pocketsphinx.h"
static const arg_t cont_args_def[] = {
POCKETSPHINX_OPTIONS,
/* Argument file. */
{"-argfile",
ARG_STRING,
NULL,
"Argument file giving extra arguments."},
{"-adcdev",
ARG_STRING,
NULL,
"Name of audio device to use for input."},
{"-infile",
ARG_STRING,
NULL,
"Audio file to transcribe."},
{"-inmic",
ARG_BOOLEAN,
"no",
"Transcribe audio from microphone."},
{"-time",
ARG_BOOLEAN,
"no",
"Print word times in file transcription."},
CMDLN_EMPTY_OPTION
};
static ps_decoder_t *ps;
static cmd_ln_t *config;
static FILE *rawfd;
static void
print_word_times()
{
int frame_rate = cmd_ln_int32_r(config, "-frate");
ps_seg_t *iter = ps_seg_iter(ps);
while (iter != NULL) {
int32 sf, ef, pprob;
float conf;
ps_seg_frames(iter, &sf, &ef);
pprob = ps_seg_prob(iter, NULL, NULL, NULL);
conf = logmath_exp(ps_get_logmath(ps), pprob);
printf("%s %.3f %.3f %f\n", ps_seg_word(iter), ((float)sf / frame_rate),
((float) ef / frame_rate), conf);
iter = ps_seg_next(iter);
}
}
static int
check_wav_header(char *header, int expected_sr)
{
int sr;
if (header[34] != 0x10) {
E_ERROR("Input audio file has [%d] bits per sample instead of 16\n", header[34]);
return 0;
}
if (header[20] != 0x1) {
E_ERROR("Input audio file has compression [%d] and not required PCM\n", header[20]);
return 0;
}
if (header[22] != 0x1) {
E_ERROR("Input audio file has [%d] channels, expected single channel mono\n", header[22]);
return 0;
}
sr = ((header[24] & 0xFF) | ((header[25] & 0xFF) << 8) | ((header[26] & 0xFF) << 16) | ((header[27] & 0xFF) << 24));
if (sr != expected_sr) {
E_ERROR("Input audio file has sample rate [%d], but decoder expects [%d]\n", sr, expected_sr);
return 0;
}
return 1;
}
/*
* Continuous recognition from a file
*/
static void
recognize_from_file()
{
int16 adbuf[2048];
const char *fname;
const char *hyp;
int32 k;
uint8 utt_started, in_speech;
int32 print_times = cmd_ln_boolean_r(config, "-time");
fname = cmd_ln_str_r(config, "-infile");
if ((rawfd = fopen(fname, "rb")) == NULL) {
E_FATAL_SYSTEM("Failed to open file '%s' for reading",
fname);
}
if (strlen(fname) > 4 && strcmp(fname + strlen(fname) - 4, ".wav") == 0) {
char waveheader[44];
fread(waveheader, 1, 44, rawfd);
if (!check_wav_header(waveheader, (int)cmd_ln_float32_r(config, "-samprate")))
E_FATAL("Failed to process file '%s' due to format mismatch.\n", fname);
}
if (strlen(fname) > 4 && strcmp(fname + strlen(fname) - 4, ".mp3") == 0) {
E_FATAL("Can not decode mp3 files, convert input file to WAV 16kHz 16-bit mono before decoding.\n");
}
ps_start_utt(ps);
utt_started = FALSE;
while ((k = fread(adbuf, sizeof(int16), 2048, rawfd)) > 0) {
ps_process_raw(ps, adbuf, k, FALSE, FALSE);
in_speech = ps_get_in_speech(ps);
if (in_speech && !utt_started) {
utt_started = TRUE;
}
if (!in_speech && utt_started) {
ps_end_utt(ps);
hyp = ps_get_hyp(ps, NULL);
if (hyp != NULL)
printf("%s\n", hyp);
if (print_times)
print_word_times();
fflush(stdout);
ps_start_utt(ps);
utt_started = FALSE;
}
}
ps_end_utt(ps);
if (utt_started) {
hyp = ps_get_hyp(ps, NULL);
if (hyp != NULL) {
printf("%s\n", hyp);
if (print_times) {
print_word_times();
}
}
}
fclose(rawfd);
}
/* Sleep for specified msec */
static void
sleep_msec(int32 ms)
{
#if (defined(_WIN32) && !defined(GNUWINCE)) || defined(_WIN32_WCE)
Sleep(ms);
#else
/* ------------------- Unix ------------------ */
struct timeval tmo;
tmo.tv_sec = 0;
tmo.tv_usec = ms * 1000;
select(0, NULL, NULL, NULL, &tmo);
#endif
}
/*
* Main utterance processing loop:
* for (;;) {
* start utterance and wait for speech to process
* decoding till end-of-utterance silence will be detected
* print utterance result;
* }
*/
static void
recognize_from_microphone()
{
ad_rec_t *ad;
int16 adbuf[2048];
uint8 utt_started, in_speech;
int32 k;
char const *hyp;
if ((ad = ad_open_dev(cmd_ln_str_r(config, "-adcdev"),
(int) cmd_ln_float32_r(config,
"-samprate"))) == NULL)
E_FATAL("Failed to open audio device\n");
if (ad_start_rec(ad) < 0)
E_FATAL("Failed to start recording\n");
if (ps_start_utt(ps) < 0)
E_FATAL("Failed to start utterance\n");
utt_started = FALSE;
E_INFO("Ready....\n");
for (;;) {
if ((k = ad_read(ad, adbuf, 2048)) < 0)
E_FATAL("Failed to read audio\n");
ps_process_raw(ps, adbuf, k, FALSE, FALSE);
in_speech = ps_get_in_speech(ps);
if (in_speech && !utt_started) {
utt_started = TRUE;
E_INFO("Listening...\n");
}
if (!in_speech && utt_started) {
/* speech -> silence transition, time to start new utterance */
ps_end_utt(ps);
hyp = ps_get_hyp(ps, NULL );
if (hyp != NULL) {
printf("%s\n", hyp);
fflush(stdout);
}
if (ps_start_utt(ps) < 0)
E_FATAL("Failed to start utterance\n");
utt_started = FALSE;
E_INFO("Ready....\n");
}
sleep_msec(100);
}
ad_close(ad);
}
int
main(int argc, char *argv[])
{
char const *cfg;
config = cmd_ln_parse_r(NULL, cont_args_def, argc, argv, TRUE);
/* Handle argument file as -argfile. */
if (config && (cfg = cmd_ln_str_r(config, "-argfile")) != NULL) {
config = cmd_ln_parse_file_r(config, cont_args_def, cfg, FALSE);
}
if (config == NULL || (cmd_ln_str_r(config, "-infile") == NULL && cmd_ln_boolean_r(config, "-inmic") == FALSE)) {
E_INFO("Specify '-infile <file.wav>' to recognize from file or '-inmic yes' to recognize from microphone.\n");
cmd_ln_free_r(config);
return 1;
}
ps_default_search_args(config);
ps = ps_init(config);
if (ps == NULL) {
cmd_ln_free_r(config);
return 1;
}
E_INFO("%s COMPILED ON: %s, AT: %s\n\n", argv[0], __DATE__, __TIME__);
if (cmd_ln_str_r(config, "-infile") != NULL) {
recognize_from_file();
} else if (cmd_ln_boolean_r(config, "-inmic")) {
recognize_from_microphone();
}
ps_free(ps);
cmd_ln_free_r(config);
return 0;
}
#if defined(_WIN32_WCE)
#pragma comment(linker,"/entry:mainWCRTStartup")
#include <windows.h>
//Windows Mobile has the Unicode main only
int
wmain(int32 argc, wchar_t * wargv[])
{
char **argv;
size_t wlen;
size_t len;
int i;
argv = malloc(argc * sizeof(char *));
for (i = 0; i < argc; i++) {
wlen = lstrlenW(wargv[i]);
len = wcstombs(NULL, wargv[i], wlen);
argv[i] = malloc(len + 1);
wcstombs(argv[i], wargv[i], wlen);
}
//assuming ASCII parameters
return main(argc, argv);
}
#endif
I can compile it by this command:
g++ -o output continuous.cpp -DMODELDIR=\"`pkg-config --variable=modeldir pocketsphinx`\" `pkg-config --cflags --libs pocketsphinx sphinxbase`
And run it by this command : output -inmic yes .
But I like to convert the code as it has no need to get inmic yes and it automatically starts the program from microphone. But I got segmentation fault(core dumped) error when I changed these parts:
static const arg_t cont_args_def= {"-inmic",
ARG_BOOLEAN,
"no",
"Transcribe audio from microphone."};
int main(int argc, char *argv[])
{
config = cmd_ln_parse_r(NULL, cont_args_def, argc, argv, TRUE);
if (cmd_ln_boolean_r(config, "-inmic")) {
recognize_from_microphone();
}
// recognize_from_microphone();
ps_free(ps);
cmd_ln_free_r(config);
return 0;
}
I searched a lot and red the documentation but couldn't understand what's the problem?
Change the last argument passed to cmd_ln_parse_r from TRUE to FALSE.
It has something to do with strict checking.
I figured this out by reading the source code for cmd_ln.c in the sphinxbase code.
I also changed the boolean value for -inmic in cont_args_def from "no" to "yes".

Searching a word in a 2d array in c programming

I am trying to set up a program that when you type /s then a movie title (ex. /s Green Mile it searches for that movie title in the movies array but my strstr function is not working. Also /a adds movie /r shows all movies in database and /q quits program.
#include <stdio.h>
#include <string.h>
main() {
char movies[1000][64];
int i;
int j = 1;
int k = 0;
int counter = 0;
char buffer[64];
char buffer2[64];
int len;
do {
printf("Enter command for movie database:\n");
fgets(buffer, 64, stdin);
if (buffer[1] == 'a') {
len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
for(i=3; i<sizeof(buffer); i++) {
movies[counter][k] = buffer[i];
k++;
}
printf("You have chosen to enter a movie in the database.\n");
printf("The movie added to the database is: %s\n", &movies[counter][0]);
counter++;
k = 0;
}
if (buffer[1] == 'q') {
printf("You have chosen to quit.\n");
printf("Goodbye.\n");
}
if (buffer[1] == 's') {
for(i=2; i<sizeof(buffer); i++) {
buffer2[k] = buffer[i];
k++;
}
for (i = 0; i < counter; i++) {
if (strstr(movies[i], buffer2) != NULL) {
printf("Found %s in position %d,%s\n", buffer2, i + 1, movies[i]);
printf("Index of Movie is %d.\n", i + 1);
}
}
k = 0;
}
if (buffer[1] == 'r') {
printf("You have choosen to report movies in database\n");
printf("These are the movies you have watched:\n");
for( i = 0; i < counter; i++ ) {
printf("%d: %s\n", j, &movies[i][0]);
j++;
}
printf("\n");
j = 1;
}
} while (buffer[1] != 'q');
}
Revised code.
#include <stdio.h>
#include <string.h>
main() {
char movies[1000][64];
int counter = 0;
char buffer[64];
char * movieTitle = &buffer[3];
while(true) {
printf("Enter command for movie database:\n");
fgets(buffer, 64, stdin);
//replace terminator every time
int len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
if(strstr(buffer, "/a") && counter < 1000) {
strcpy(movies[counter], movieTitle);
printf("You have chosen to enter a movie in the database.\n");
printf("The movie added to the database is: %s\n", &movies[counter][0]);
counter++;
}
else if (strstr(buffer, "/s")) {
for (int i = 0; i < counter; i++) {
if (strcmp(movies[i], movieTitle) == 0) {
printf("Found %s in position %d,%s\n", movieTitle, i + 1, movies[i]);
printf("Index of Movie is %d.\n", i + 1);
}
}
}
else if (strstr(buffer, "/r")) {
printf("You have choosen to report movies in database\n");
printf("These are the movies you have watched:\n");
for( i = 0; i < counter; i++ ) {
printf("%d: %s\n", i + 1, &movies[i][0]);
}
printf("\n");
}
else if (strstr(buffer, "/q")) {
printf("You have chosen to quit.\n");
printf("Goodbye.\n");
break;
}
else {
printf("unrecognized command");
}
}
}

Factorial in bignum library

Ive tried to create my own implementation of a bignum library
I cant seem to get the factorial to work. If I ask it to solve 4!, it gives out 96. It multiplies 4 twice. similarly, 5! is 600, not 120. I haven't implemented division, so I cant/dont want to divide the answer by the number
//bignum project
#include <iostream>
using namespace std;
class bignum
{
public:
int number[100];
int dpos;
int operator/ (bignum);
bignum operator- (bignum);
bignum operator* (bignum);
bignum operator+ (bignum);
bignum operator= (string);
void output()
{
int begin=0;
for(int i=0; i<=99; i++)
{
if(number[i]!=0 || begin==1)
{
cout<<number[i];
begin=1;
}
}
}
};
bool num_is_zero(bignum k)
{
for(int a=0; a<=99; a++)
{
if(k.number[a]!=0)
{
return false;
}
}
return true;
}
bignum factorial(bignum a)
{
bignum j;
bignum fact;
fact="1";
while(!num_is_zero(a))
{
j="1";
fact=fact*a;
a=a-j;
}
return fact;
}
bignum bignum::operator= (string k)
{
int l;
l=k.length()-1;
for(int h=0; h<=99; h++)
{
number[h]=0;
}
for(int a=99; a>=0 && l>=0; a--)
{
number[a]=k[l]-'0';
l--;
}
}
bignum bignum::operator+ (bignum b)
{
bignum a;
int carry=0;
for(int k=0; k<=99; k++)
{
a.number[k]=0;
}
for(int i=99; i>=0; i--)
{
a.number[i]= number[i]+b.number[i]+a.number[i];
if(a.number[i]>9)
{
carry=(a.number[i]/10);
a.number[i-1]+=carry;
a.number[i]=(a.number[i]%10);
}
}
return (a);
}
bignum bignum::operator- (bignum c)
{
bignum a;
int sign=0;
for(int k=0; k<=99; k++)
{
a.number[k]=0;
}
for(int i=99; i>=0; i--)
{
if(number[i]<c.number[i])
{
number[i]+=10;
if(i!=0)
number[i-1]--;
}
a.number[i]=number[i]-c.number[i];
}
return (a);
}
bignum bignum::operator* (bignum b)
{
bignum ans;
int ans_grid[100][100],x,lines=0,carry,sum[100];
for(int a=0; a<=99; a++)
{
for(int b=0; b<=99; b++)
{
ans_grid[a][b]=0;
}
}
for(int i=99; i>=0; i--)
{
for(int j=i,x=99; j>=0; j--,x--)
{
ans_grid[lines][j]=(number[i]*b.number[x]);
}
lines++;
}
//------------------------------------------------Carry Forward and assign to ans------------------------------------------------//
for(int j=99; j>=0; j--)
{
for(int i=99; i>=0; i--)
{
if(ans_grid[j][i]>9 && i!=0)
{
carry=(ans_grid[j][i]/10);
ans_grid[j][i-1]+=carry;
ans_grid[j][i]%=10;
}
}
}
for(int col=99; col>=0; col--)
{
for(int row=99; row>=0; row--)
{
sum[col]+=ans_grid[row][col];
}
}
for(int i=99; i>=0; i--)
{
if(sum[i]>9 && i!=0)
{
carry=(sum[i]/10);
sum[i-1]+=carry;
sum[i]%=10;
}
}
for(int l=0; l<=99; l++)
ans.number[l]=sum[l];
//-------------------------------------------------------------------------------------------------------------------------------//
return (ans);
}
I think your problem is that sum is uninitialized in your operator*. I'm reluctant to give a partial answer, since I took the code and fiddled with it a bit, so here's my version which appears to work (and also prints "0" correctly):
Update: I couldn't resist making several structural improvements. I didn't touch your multiplication routine, so you should still be able to extract the bugfix even if you don't care for the rest.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class bignum
{
public:
int number[100];
bignum() { std::fill(number, number + 100, 0); }
bignum(const bignum & other) { std::copy(other.number, other.number + 100, number); }
bignum(const std::string &);
bignum & operator-=(const bignum &);
inline bignum operator-(const bignum & c) const { return bignum(*this) -= c; }
bignum operator*(const bignum &) const;
inline bignum & operator= (const std::string & k) { return *this = bignum(k); }
inline operator bool() const
{
for (size_t a = 0; a < 100; ++a)
if (number[a] != 0) return true;
return false;
}
};
std::ostream & operator<<(std::ostream & o, const bignum & b)
{
bool begun = false;
for (size_t i = 0; i < 100; ++i)
{
if (begun || b.number[i] != 0)
{
cout << b.number[i];
begun = true;
}
}
if (!begun) o << "0";
return o;
}
bignum::bignum(const std::string & k)
{
std::fill(number, number + 100, 0);
for(size_t h = 0; h < std::min(k.length(), 100U); ++h)
number[99 - h] = k[k.length() - 1 - h] - '0';
}
bignum & bignum::operator-=(const bignum & c)
{
for (int i = 99; i >= 0; --i)
{
if (number[i] < c.number[i])
{
number[i] += 10;
if (i != 0) --number[i-1];
}
number[i] -= c.number[i];
}
return *this;
}
bignum bignum::operator*(const bignum & b) const
{
bignum ans;
int ans_grid[100][100], lines = 0, carry, sum[100];
std::fill(sum, sum + 100, 0);
for (size_t i = 0; i < 100; ++i) std::fill(ans_grid[i], ans_grid[i] + 100, 0);
for(int i=99; i>=0; i--)
{
for(int j=i,x=99; j>=0; j--,x--)
{
ans_grid[lines][j]=(number[i]*b.number[x]);
}
lines++;
}
//------------------------------------------------Carry Forward and assign to ans------------------------------------------------//
for(int j=99; j>=0; j--)
{
for(int i=99; i>=0; i--)
{
if(ans_grid[j][i]>9 && i!=0)
{
carry=(ans_grid[j][i]/10);
ans_grid[j][i-1]+=carry;
ans_grid[j][i]%=10;
}
}
}
for(int col=99; col>=0; col--)
{
for(int row=99; row>=0; row--)
{
sum[col]+=ans_grid[row][col];
}
}
for(int i=99; i>=0; i--)
{
if(sum[i]>9 && i!=0)
{
carry=(sum[i]/10);
sum[i-1]+=carry;
sum[i]%=10;
}
}
for(int l=0; l<=99; l++)
ans.number[l]=sum[l];
//-------------------------------------------------------------------------------------------------------------------------------//
return (ans);
}
bignum factorial(bignum a)
{
bignum j; j = "1";
bignum fact; fact="1";
while(a)
{
fact = fact * a;
a = a-j;
}
return fact;
}
int main(int argc, char * argv[])
{
if (argc < 2) return 0;
bignum a;
a = std::string(argv[1]);
bignum b = factorial(a);
cout << a << std::endl << b << std::endl;
}
The string assignment is still broken for strings with more than one digit, but that wasn't your question I suppose...