std::out_of_range for C++ code - c++

I am having errors running this code. While executing it gives out an error like-
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Any ideas on what I am doing wrong here?
#include <string.h>
#include <cstring>
#include <string>
#include <iostream>
#include <fstream>
#include "fix_nvt.h"
#include "group.h"
#include "modify.h"
#include "error.h"
using namespace LAMMPS_NS;
using namespace FixConst;
using namespace std;
std::ifstream inFile;
double x,y,z;
string str_val;
/* ---------------------------------------------------------------------- */
FixNVT::FixNVT(LAMMPS *lmp, int narg, char **arg) :
FixNH(lmp, narg, arg)
{
if (!tstat_flag)
error->all(FLERR,"Temperature control must be used with fix nvt");
if (pstat_flag)
error->all(FLERR,"Pressure control can not be used with fix nvt");
// create a new compute temp style
// id = fix-ID + temp
int n = strlen(id) + 6;
id_temp = new char[n];
strcpy(id_temp,id);
strcat(id_temp,"_temp");
char **newarg = new char*[3];
newarg[0] = id_temp;
newarg[1] = group->names[igroup];
newarg[2] = (char *) "temp";
modify->add_compute(3,newarg);
delete [] newarg;
tflag = 1;
printf("syracuse rocks\n\n\n");
inFile.open("matrix.txt", ios::in);
while(getline(inFile,str_val));
{
x = atof(str_val.substr(1,4).c_str());
y = atof(str_val.substr(17,4).c_str());
z = atof(str_val.substr(33,4).c_str());
printf ("x = %f, y =%f, z=%f\n",x,y,z);
}
inFile.close();
}

Related

My application name changes after runtime, but it has no file extension, I want it to be in .exe

My application name changes after runtime, but it has no file extension. I want it to be an .exe.
I'm new to c++ and I really need to figure this out.
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
std::string path()
{
char shitter[_MAX_PATH]; // defining the path
GetModuleFileNameA(NULL, shitter, _MAX_PATH); // getting the path
return std::string(shitter); //returning the path
}
int main()
{
srand(time(NULL));
char letter = 'A' + (rand() % 26);
const char *val = new char(letter);
std::rename(path().c_str(), val); //renaming the file
}
I tried doing this
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
std::string path()
{
char shitter[_MAX_PATH]; // defining the path
GetModuleFileNameA(NULL, shitter, _MAX_PATH); // getting the path
return std::string(shitter); //returning the path
}
int main() {
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); // Higher Priority
SetConsole();
srand(time(NULL));
char letters = 'A'+ (rand() % 26);
const char* val = new char(letters);
std::string rename(path().c_str(), val += ".exe"); //renaming the file
But now im getting an error
https://prnt.sc/uejlxz
rename(path().c_str(), val + ".exe")
or use append
String Concatenation

Segmentation fault in array storing in IPC linux

I am trying to store a array in shared from a process and tring to access the same from another process.
Below is the code I am using to store the array
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int count;
int main()
{
while(1)
{
int arr[5] = {1,2,3,4,5};
int *str1;
int key=5678;
// shmget returns an identifier in shmid
int shmid = shmget(key,1024, 0666|IPC_CREAT);
printf("\nShared Memory Id = %d\n",shmid);
// shmat to attach to shared memory
str1 = (int*) shmat(shmid,(void*)0,0);
for(int i=0;i<5;i++)
{
*str1=arr[i];
printf("Data written in memory: %d\n",*str1);
str1++;
}
}
shmdt((void*)str);
return 0;
}
When I am running the program, it is running upto some extend and giving error as segmentation fault (core dumped) and getting exit from the application.
Please help me to solve this problem.
Thanks and regards,
Prabhakar M
str1++ is the culprit.
Below code is working.
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int count;
int main()
{
int arr[5] = {1,2,3,4,5};
int *str1;
int key=5678;
// shmget returns an identifier in shmid
int shmid = shmget(key,1024, 0666|IPC_CREAT);
printf("\nShared Memory Id = %d\n",shmid);
// shmat to attach to shared memory
str1 = (int*) shmat(shmid,(void*)0,0);
int *copyAdrr;
copyAdrr = str1 ;
while(1)
{
for(int i=0;i<5;i++)
{
*str1=arr[i];
printf("Data written in memory: %d\n",*str1);
str1++;
}
str1 =copyAdrr;
}
shmdt((void*)str);
return 0;
}

c++ put functions in separate source files

Currently I have an unique source file (*.cpp) where all my functions are working right. Now i'm trying to take some of them out into separate source files and including them into main source with no success.
My current project is as follows:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
using namespace std;
using std::cout;
using std::ifstream;
/*This is one of the functions to be put in separate file:*/
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15;
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre);
if (inputFile.is_open())
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End of function 'ReadPageAsignations'
/*This is another function where my function "ReadPageAsignations' get called -- btw, I want also this function to be in a separate source file.*/
void DeliverHtml (const char* page){//const char* RutayNombre ) {
string *p;
char * pch;
size_t pos;
string RutayNombre;
RutayNombre = "../Substructure/Templates/" + SearchConfigValue( "../Substructure/Conf/Config-Templates.txt", "htmlTemplate:");
const char *RutayNombreConfigCompos = "../Substructure/Conf/Config-Composition.txt";
string RutayNombreParaInsertar;
string token, token1, token2;
string line, lineRead, lineToInsert;
char * StrToTokenize2;
string StrToTokenize1;
p=ReadPageAsignations( RutayNombreConfigCompos, page); //Here, I call the function I want in a separate file
...
}
/*And here is the main() function*/
int main()
{
char *value = "page=Home";
if (NULL!=strstr(getenv("QUERY_STRING"), "page="))
{
value = getenv("QUERY_STRING");
}
char *posCh = strstr(value, "=");
DeliverHtml(&posCh[0]+1);
return 0;
}
For the first function, I have tried creating the header file 'ReadPageAsignations.h' and a source file 'ReadPageAsignations.cpp'.
Header file 'ReadPageAsignations.h' containing:
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
Source file 'ReadPageAsignations.cpp' for separate function containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using std::cout;
using std::ifstream;
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15; /*El numero de elementos debe coincidir con el iterador en la función Deliverhtml.*/
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre); //Abre el archivo y lo asigna al stream inputFile.
if (inputFile.is_open()) //Chequea que el archivo esté abierto.
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End function
and, main project containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h" //Here I #include the function definition file (header)
using namespace std;
using std::cout;
using std::ifstream;
...
}
I've got a lot of compiling errors:
\ReadPageAsignations.h|4|error C2143: syntax error : missing ';' before '*'|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
main.cpp|20|error C2872: 'string' : ambiguous symbol|
...
I'm working Code::blocks 13.12 with MS Visual C++ 2005/2008 compiler.
any help will be highly appreciated, thanks in advance.
The error is telling you that when it tried to parse the header file it encountered the symbol string and doesn't recognize it. Adding #include <string> to your header file and fully qualifying the string type as std::string should correct the problem.
You should put #include <string> in your header file and remove it from your .cpp file
as following:
main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h"
...
note: including header file with the same name of .cpp file , include both.
ReadPageAsignations.h
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
#include <string> //<-----This line, include string header
std::string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
ReadPageAsignations.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include "ReadPageAsignations.h" // <--- add the header file here
//#include <string> <---remove it already included in the header file
using namespace std;
//using std::cout; <--remove this you already used namespace std
//using std::ifstream; <--remove this you already used namespace std
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
... } //End function

Setenv: Type expression list treated as compound expression in initializer

Getting Type expression list treated as compound expression in initializer
On both these function calls -
char itoa(new_total, new_total_ch, 10);
int setenv("COUNT_TOTAL", new_total_ch, 1);
Here's the code snippet -
#include <iostream>
// create process team
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctime>
// initialize & process
#include <time.h>
#include <string>
#include <fstream>
#include <cmath>
#include <iosfwd>
// initialize & process
using std::ifstream;
using namespace std;
class Count3sProcessParallel {
public:
//int process();
int pr_count;
int process();
typedef int COUNT_TOTAL;
private:
int worker;
//declare process()
long unit_of_work;
long lower_bound;
long upper_bound;
int pr_i;
char * ct;
int ct_i;
int new_total;
char itoa();
char * new_total_ch;
int setenv();
};
int Count3sProcessParallel::process() {
// determine upper lower bounds
unit_of_work = in_length/workers_num;
lower_bound = (worker -1) * unit_of_work;
upper_bound = (worker * unit_of_work) -1;
// iterate and count
pr_count = 0;
for (pr_i = lower_bound; pr_i < upper_bound; pr_i++)
if (floor(in_buffer[pr_i] == 3))
pr_count++;
return pr_count;
//update COUNT_TOTAL
ct = getenv("COUNT_TOTAL");
ct_i = atoi(ct);
new_total = (pr_count + ct_i);
char * new_total_ch[33];
char itoa(new_total, new_total_ch, 10);
int setenv("COUNT_TOTAL", new_total_ch, 1);
delete[] in_buffer;
return 0;
}
How do I resolve this? Thanks.
Remove the leading types. Just use:
itoa(new_total, new_total_ch, 10);
setenv("COUNT_TOTAL", new_total_ch, 1);

failing to parse C++ using llvm and clang

I'm writing a little tool with llvm to parse C and C++ code, but I can't seem to get it to successfully parse C++ at all. I'm probably missing something obvious.
This is what I have so far:
#include <iostream>
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/LangStandard.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Parse/ParseAST.h"
class MyASTConsumer : public clang::ASTConsumer {
public:
bool HandleTopLevelDecl(clang::DeclGroupRef d);
virtual ~MyASTConsumer() { }
};
bool MyASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d)
{
for(auto ii = d.begin(); ii != d.end(); ii++)
{
printf("decl type: %s\n", (*ii)->getDeclKindName());
auto namedDecl = llvm::dyn_cast<clang::NamedDecl>(*ii);
if(namedDecl)
{
printf("name: %s\n", namedDecl->getName().data());
}
}
return true;
}
int main(int, char **argv)
{
using clang::CompilerInstance;
using clang::TargetOptions;
using clang::TargetInfo;
using clang::FileEntry;
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
using clang::SrcMgr::CharacteristicKind;
using clang::StringRef;
using clang::DirectoryLookup;
using llvm::MemoryBuffer;
using clang::LangOptions;
using clang::FrontendOptions;
using clang::LangStandard;
using clang::CompilerInvocation;
using clang::InitializePreprocessor;
using clang::Preprocessor;
using clang::PreprocessorOptions;
using clang::HeaderSearch;
using clang::HeaderSearchOptions;
CompilerInstance ci;
DiagnosticOptions diagnosticOptions;
ci.createDiagnostics();
CompilerInvocation *invocation = new CompilerInvocation;
LangOptions &langOpts = ci.getLangOpts();
langOpts.RTTI = 1;
langOpts.Bool = 1;
langOpts.CPlusPlus11 = 1;
langOpts.GNUKeywords = 1;
langOpts.CXXExceptions = 1;
langOpts.POSIXThreads = 1;
langOpts.SpellChecking = 1;
invocation->setLangDefaults(langOpts, clang::IK_CXX, LangStandard::lang_gnucxx11);
ci.setInvocation(invocation);
llvm::IntrusiveRefCntPtr<TargetOptions> pto( new TargetOptions() );
pto->Triple = llvm::sys::getDefaultTargetTriple();
llvm::IntrusiveRefCntPtr<TargetInfo> pti(TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto.getPtr()));
ci.setTarget(pti.getPtr());
ci.createFileManager();
auto &fileManager = ci.getFileManager();
ci.createSourceManager(fileManager);
llvm::IntrusiveRefCntPtr<HeaderSearchOptions> headerSearchOpts( new HeaderSearchOptions() );
ci.createPreprocessor();
auto &pp = ci.getPreprocessor();
pp.setPredefines(builtinMacros);
HeaderSearch &headerSearch = pp.getHeaderSearchInfo();
for(auto &inc: builtinIncludePaths)
{
auto dirEntry = fileManager.getDirectory(StringRef(inc), true);
DirectoryLookup dirLookup(dirEntry, CharacteristicKind::C_System, false);
headerSearch.AddSearchPath (dirLookup, true);
}
MyASTConsumer *astConsumer = new MyASTConsumer();
ci.setASTConsumer(astConsumer);
ci.createASTContext();
const FileEntry *pFile = fileManager.getFile(argv[1]);
auto &sourceManager = ci.getSourceManager();
sourceManager.createMainFileID(pFile);
ci.getDiagnosticClient().BeginSourceFile(
ci.getLangOpts(),
&pp
);
clang::ParseAST(pp, astConsumer, ci.getASTContext());
ci.getDiagnosticClient().EndSourceFile();
return 0;
}
It does parse C just fine, but it errors out on the namespace keyword and extern "C" { blocks. So far I'm stumped. If anyone has a clue, something I'm missing, please share.
I believe I figured out the problem. You should always call setInvocation on the compiler instance before calling a lot of the methods on the compiler instance, as it actually just proxies to the invocation.
I moved the setInvocation call to right after the CompilerInvocation object is created, and things now work.