How do I set up a function to convert vector of strings to vector of integers in VC++? - string

The question is in the title. Need help figuring out why my code compiles but doesn't work as intended. Thanks!
//This example demonstrates how to do vector<string> to vectro<int> conversion using a function.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
vector<int>* convertStringVectorToIntVector (vector<string> *vectorOfStrings)
{
vector<int> *vectorOfIntegers = new vector<int>;
int x;
for (int i=0; i<vectorOfStrings->size(); i++)
{
stringstream str(vectorOfStrings->at(i));
str >> x;
vectorOfIntegers->push_back(x);
}
return vectorOfIntegers;
}
int main(int argc, char* argv[]) {
//Initialize test vector to use for conversion
vector<string> *vectorOfStringTypes = new vector<string>();
vectorOfStringTypes->push_back("1");
vectorOfStringTypes->push_back("10");
vectorOfStringTypes->push_back("100");
delete vectorOfStringTypes;
//Initialize target vector to store conversion result
vector<int> *vectorOfIntTypes;
vectorOfIntTypes = convertStringVectorToIntVector(vectorOfStringTypes);
//Test if conversion is successful and the new vector is open for manipulation
int sum = 0;
for (int i=0; i<vectorOfIntTypes->size(); i++)
{
sum+=vectorOfIntTypes->at(i);
cout<<sum<<endl;
}
delete vectorOfIntTypes;
cin.get();
return 0;
}

The code above has only one problem: You are deleting your vectorOfStringTypes before you pass it to your conversion function.
Move the line delete vectorOfStringTypes; to after you have called your convert function and the program works as intended.

Related

Get function from x64 instruction pointers?

This is an exercise that I want to implement in real code
I send a signal to my app (x86-64 linux). My app then executes code that walks the stack and prints out instruction pointers. I'm not sure if I want only the last few or everything to main. Anyway, I'm releasing an optimized binary without debug information. I strip symbols before its distributed.
I was wondering, how do I translate it back? I don't need to translate it in the app. I can use the machine I build to go from rip's to functions. I was thinking maybe I should also distribute one with debug information and maybe have the user be able to see the function+line but I think line will be unlikely if its optimized well
Another problem I have is my code doesn't seem to walk past the signal function. backtrace figures it out but I'm trying to do this without libc. Here's some code
#include <signal.h>
#include <cstdio>
typedef unsigned long long u64;
int mybacktrace();
#include <execinfo.h>
#include <unistd.h>
void print_stacktrace(void) {
size_t size;
enum Constexpr { MAX_SIZE = 1024 };
void *array[MAX_SIZE];
size = backtrace(array, MAX_SIZE);
backtrace_symbols_fd(array, size, STDOUT_FILENO);
}
void mysig(int signo) {
mybacktrace();
_exit(1);
}
int mybacktrace() {
u64*p;
p = (u64*)((u64)&p + 16); //seems to work correctly
for (int i = 0; i < 10 && (u64)p >= 1<<16; i++)
{
printf("%d %p\n", i, p[1]);
p = (u64*)(p[0]);
}
print_stacktrace(); return 0;
return 0;
}
int test()
{
return mybacktrace();
}
int main(int argc, char *argv[])
{
signal(SIGILL, mysig);
test();
__builtin_trap();
return 0;
}

ICU4C austrdup function

I'm trying to run the code demo for ICU4C bellow, and getting
warning: implicit declaration of function 'austrdup'
which subsequently generate an error. I understand that this is due to the missing imported library that contains 'austrdup' function, and have been looking at the source code to guess which one it is, but no luck. Does anyone have any idea which one should be imported?
#include <unicode/umsg.h>
#include <unicode/ustring.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
UChar* str;
UErrorCode status = U_ZERO_ERROR;
UChar *result = NULL;
UChar pattern[100];
int32_t resultlength, resultLengthOut, i;
double testArgs[] = { 100.0, 1.0, 0.0};
str=(UChar*)malloc(sizeof(UChar) * 10);
u_uastrcpy(str, "MyDisk");
u_uastrcpy(pattern, "The disk {1} contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}");
for(i=0; i<3; i++){
resultlength=0;
resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, testArgs[i], str);
if(status==U_BUFFER_OVERFLOW_ERROR){ //check if output truncated
status=U_ZERO_ERROR;
resultlength=resultLengthOut+1;
result=(UChar*)malloc(sizeof(UChar) * resultlength);
u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, testArgs[i], str);
}
printf("%s\n", austrdup(result) ); //austrdup( a function used to convert UChar* to char*)
free(result);
}
return 0;
}
austrdup is not an official ICU method. It's only used by tests in ICU and defined in icu4c/source/test/cintltst/cintltst.h and implemented in icu4c/source/test/cintltst/cintltst.c. It is bascially just a wrapper around u_austrcpy.

Piping in shell

i have created my own shell in linux. it works fine with commmands. Now I want to add pipes in it. i want to implement multiple piping in it. Can some one guide me how to do do? I havent used Linux. Iam new to it.
I have seen many source codes and sites but i am still not clear about the idea of executing commands having multiple pipes!
This is code i have implemented so far!
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
using namespace std;
int main ()
{
while (true){
char * input;
string insert;
char * token;
char * parsed[9];
int count=0;
char * cmd1[6];
char * cmd2[6];
cout<<"My Shell $";
getline(cin,insert); // take input from user
input= new char [insert.size()+1];
strcpy(input, insert.c_str());
for (int i=0; i<9; i++)
parsed[i]=NULL;
token=strtok(input, " ");
while (token!=NULL) // parse the input
{
parsed[count] = new char[strlen(token) + 1];
strcpy(parsed[count++],token);
token=strtok(NULL, " ");
}
delete input;
delete token;
int j= count-1;
int pipe_position[4]={0};
int counter=0;
for (int i=0; i<j; i++) // finding position of pipe
{
if ((strcmp(parsed[i],"|"))==0)
pipe_position[counter++]=i;
}
bool pipe_exists=false;
if (pipe_position[0]!=0)
pipe_exists=true;
if(pipe_exists==false) // if there isnt any pipe in the command
{
pid_t mypid=fork();
if (mypid==0)
{
execlp (parsed[0],parsed[0],parsed[1],parsed[2],parsed[3],parsed[4], parsed[5],parsed[6],parsed[7],parsed[8],(char*) NULL);
}
else if (mypid>0)
{
wait(NULL);
for(int i=0; i<9; i++)
delete[]parsed[i];
}
}
} //end of while
}

Problems when reading integers with scanf

I know that it might be a stupid question but can you tell me why the following patch of code fails? I see nothing wrong. I am trying to read integers using scanf. I have included the necessary library, but when I run the program it crashes after I read the first s. Thank you.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <vector>
using namespace std;
int main()
{
int n, x;
scanf("%d", &n); scanf("%d", &x);
vector< pair<int, int> > moments;
for(int i = 0; i < n; ++i)
{
int f, s;
scanf("%d", &f);
scanf("%d", &s );
moments[i].first = f;
moments[i].second = s;
}
return 0;
}
That is not the way to assign values to moments since moments[i] does not yet exist. Try:
pair<int, int> thing;
thing = make_pair(f,s);
moments.push_back(thing);
instead of your assignements to moments elements.

Good way to tokenize line from file without using external libraries?

I am trying to tokenize a database dump separated by commas. I only need to read the first word, which will tell me if this is the line I need and then tokenize the line and save each separated string in a vector.
I have had trouble keeping all of the datatypes in order. I use a method of getline:
string line;
vector<string> tokens;
// Iterate through each line of the file
while( getline( file, line ) )
{
// Here is where i want to tokenize. strtok however uses a character array and not a string.
}
The thing is, I only want to continue reading and tokenize a line if the first word is what I am after. Here is a sample of a line from the file:
example,1,200,200,220,10,550,550,550,0,100,0,-84,255
So, if I am after the string example, it goes ahead and tokenizes the rest of the line for my use and then stops reading from the file.
Should I be using strtok, stringstream or something else?
Thank you!
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void do(ifstream& file) {
string line;
string prefix = "example,";
// Get all lines from the file
while (getline(file,line).good()) {
// Compare the beginning for your prefix
if (line.compare(0, prefix.size(), prefix) == 0) {
// Homemade tokenization
vector<string> tokens;
int oldpos = 0;
int pos;
while ((pos = line.find(',', oldpos)) != string::npos) {
tokens.push_back(line.substr(oldpos, pos-oldpos));
oldpos = pos + 1;
}
tokens.push_back(line.substr(oldpos)); // don't forget the last bit
// And here you are!
}
}
}
How do I tokenize a string in C++?
http://www.daniweb.com/software-development/cpp/threads/27905
Hope this helps, though I am not proficient C/C++ programmer. For the record it would be nice if you could specify in the tags or in post language you are using.
Tokenizer.h
#ifndef TOKENIZER_H
#define TOKENIZER_H
#include <string>
#include <vector>
#include <sstream>
class Tokenizer
{
public:
Tokenizer();
~Tokenizer();
void Tokenize(std::string& str, std::vector<std::string>& tokens);
};
#endif /* TOKENIZER_H */
Tokenizer.cpp
#include "Tokenizer.h"
using namespace std;
string seps(string& s) {
if (!s.size()) return "";
stringstream ss;
ss << s[0];
for (int i = 1; i < s.size(); i++)
ss << '|' << s[i];
return ss.str();
}
void tok(string& str, vector<string>& tokens, const string& delimiters = ",")
{
seps(str);
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
}
Tokenizer::Tokenizer()
{
}
void Tokenizer::Tokenize(string& str, vector<string>& tokens)
{
tok(seps(str), tokens);
}
Tokenizer::~Tokenizer()
{
}
To tokenize a string
#include "Tokenizer.h"
#include <string>
#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
// Required variables for later below
vector<string> t;
string s = "This is one string,This is another,And this is another one aswell.";
// What you need to include:
Tokenizer tokenizer;
tokenizer.Tokenize(s, t); // s = a string to tokenize, t = vector to store tokens
// Below is just to show the tokens in the vector<string> (c++11+)
for (auto c : t)
cout << c << endl;
system("pause");
return 0;
}

Resources