i'm trying to turn a 1d array of strings into a 2d array of chars using:
'''''''''''''''
variables
'''''''''''''''
const int width = 20;
const int height = 20;
char arena[width][height];
string arenaline[height];
'''''''''''''''
setup
'''''''''''''''
arenaline[1] = "####################";
arenaline[2] = "#..................#";
arenaline[3] = "#..................#";
arenaline[4] = "###...###..###...###";
arenaline[5] = "#.......#..#.......#";
arenaline[6] = "###...###..###...###";
arenaline[7] = "#..................#";
arenaline[8] = "###...###..###...###";
arenaline[9] = "#.......#..#.......#";
arenaline[10] = "#########..#########";
arenaline[11] = "###..............###";
arenaline[12] = "###.#####..#####.###";
arenaline[13] = "###.####....####.###";
arenaline[14] = "###.####....####.###";
arenaline[15] = "#.....###..###.....#";
arenaline[16] = "#.....###..###.....#";
arenaline[17] = "#..#..###..###..#..#";
arenaline[18] = "#.....###..###.....#";
arenaline[19] = "#.....###..###.....#";
arenaline[20] = "####################";
'''''''''''''''
conversion
'''''''''''''''
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
arena[j][i] = arenaline[i].substr(j,1);
}
}
I want it to convert from the substring to a char so I can use it in an array.
I can't use a string instead of chars because it breaks the function where the array is output to the console.
substr returns a string. string is not implicitly converted to char for "single character" strings.
The correct way to adress single characters of strings is string::operator[] or string::at().
Related
My problem is that the variable 'scoreA' should be the accumulation of all the values generated during each iteration of the for loop. However, I am not getting the accumulated value and get only the value at the final iteration. Could someone Kindly help me out as I am new to C++. I have defined scoreA outside the for loop so my understanding is that the value of scoreA should be the accumulated value for all the iterations. But my guess is that it is being reassigned to 0 because of which it is unable to accumulate the value.
#include<iostream>
#include<map>
#include<string>
using namespace std;
map<string,int> Score_Scheme;
string StringA = "aaaa";
int Score_Compute(string StringA);
int Base_case_A(int lenA);
int main ()
{
Score_Scheme["ac"] = -1;
Score_Scheme["ag"] = -2;
Score_Scheme["at"] = -1;
Score_Scheme["a-"] = -3;
Score_Scheme["cg"] = -3;
Score_Scheme["ct"] = -2;
Score_Scheme["c-"] = -4;
Score_Scheme["gt"] = -2;
Score_Scheme["g-"] = -2;
Score_Scheme["t-"] = -1;
Score_Scheme["--"] = 0;
Score_Scheme["aa"] = 5;
Score_Scheme["cc"] = 5;
Score_Scheme["gg"] = 5;
Score_Scheme["tt"] = 5;
Score_Scheme["ca"] = -1;
Score_Scheme["ga"] = -2;
Score_Scheme["ta"] = -1;
Score_Scheme["-a"] = -3;
Score_Scheme["gc"] = -3;
Score_Scheme["tc"] = -2;
Score_Scheme["-c"] = -4;
Score_Scheme["tg"] = -2;
Score_Scheme["-g"] = -2;
Score_Scheme["-t"] = -1;
int len_StringA = StringA.size ();
cout<<"length of A is:"<<len_StringA<<"\n";
Base_case_A(len_StringA);
return 0;
}
int Base_case_A(int lenA)
{
int scoreA = 0;
for(int i = 0;i<lenA;i++)
{
char x[2];
x[0] = StringA[i];
x[1] = '-';
scoreA=scoreA+Score_Compute(x);
cout<<i<<":"<<scoreA<<"\n";
}
cout<<scoreA<<"\n";
return 0;
}
int Score_Compute(string stringA)
{
return Score_Scheme[stringA];
}
Score_Compute() takes a std::string as input, but when the loop calls Score_Compute(x), x is a char[2] containing 2 char values neither of which are a null terminator.
When a char[] is passed as-is to a std::string, the char[] decays to char*, which std::string then assumes to be null-terminated, which yours is not.
So, the std::string that Score_Compute() receives will be wrong, usually containing random data after the characters you did specify (assuming the code doesn't just crash altogether while searching for a null terminator that doesn't exist), and so it will not match any entries in your std::map, causing Score_Compute() to return 0.
To fix the logic, you need to change the declaration of x to char x[3]; and then add x[2] = '\0'; before converting to std::string:
char x[3]; // <-- fix this!
x[0] = StringA[i];
x[1] = '-';
x[2] = '\0'; // <-- add this!
Otherwise, you have to specify the correct length when converting to std::string:
Score_Compute(string(x, 2));
Alternatively, simply change x to be a std::string to begin with:
string x(2, '\0');
x[0] = StringA[i];
x[1] = '-';
Or:
string x;
s.resize(2);
x[0] = StringA[i];
x[1] = '-';
Or:
string x = " -";
x[0] = StringA[i];
I've a written a function to calculate the correlation matrix for variables (risks) held in a flat file structure. I.e. RiskID | Year | Amount
I have written the function because the library routines that I can find necessitate a matrix input. That is, RiskID as 2nd dimension and year as the 1st dimension - with amounts as actual array values. The matrix needs to be complete, in that zero values must be included also and hence for sparsely populated non zero data - this leads to wasted iterations which can be bypassed. The routine relies upon the data being sorted first by Year (asc) then by RiskID (asc)
I have written the routine in C++ (for speed) to be compiled as a dll and referenced in VB.NET. I need to pass 3 arrays (one each for each of the headers) and return a 2 dimensional array back to VB.NET. I guess I'm cheating by passing 3 individual 1d arrays instead of a 2d array but there you go. I'll post the full C++ routine as others may find it useful if seeking to do something similar. I'd be surprised if this hasn't been done before - but I just can't find it.
I lack the interop knowledge to implement this properly and am getting nowhere googling around. As far as I can workout I may need to use SAFEARRAY ?
Or is there a quick fix to this problem? Or is SAFEARRAY a piece of cake. Either way an example would be very helpful.
Also, as a side note - I'm sure the memory management is failing somewhere?
Here is the Visual C++ (VS2013)
Header File
#ifndef CorrelLib_EXPORTS
#define CorrelLib_API __declspec(dllexport)
#else
#define CorrelLib_API __declspec(dllimport)
#endif
// Returns correlation matrix for values in flat file
extern "C" CorrelLib_API double** __stdcall CalcMatrix(int* Risk, int* Year, double* Loss, const int& RowNo, const int& RiskNo, const int& NoSimYear);
CPP File
#include "stdafx.h"
#include "CorrelLib.h"
#include <memory>
#include <ctime>
using namespace std;
extern "C" CorrelLib_API double** __stdcall CalcMatrix(int* Risk, int* Year, double* Loss, const int& RowNo, const int& RiskNo, const int& NoSimYear)
{
int a, b;
int i, j, k;
int YearCount, MissingYears;
int RowTrack;
//Relies on Year and Risk being sorted in ascending order in those respective orders Year asc, Risk asc
double *RiskTrack = new double[RiskNo](); //array of pointers?
int *RiskTrackBool = new int[RiskNo](); //() sets inital values to zero
double *RiskAvg = new double[RiskNo]();
double *RiskSD = new double[RiskNo]();
//Create 2d array to hold results 'array of pointers to 1D arrays of doubles'
double** Res = new double*[RiskNo];
for (i = 0; i < RiskNo; ++i)
{
Res[i] = new double[RiskNo](); //()sets initial values to zero
}
//calculate average
for (i = 0; i < RowNo; i++)
{
a = Risk[i];
RiskAvg[a] = RiskAvg[a] + Loss[i];
}
for (i = 0; i < RiskNo; i++)
{
RiskAvg[i] = RiskAvg[i] / NoSimYear;
}
//Enter Main Loop
YearCount = 0;
i = 0; //start at first row
do {
YearCount = YearCount + 1;
a = Risk[i];
RiskTrack[a] = Loss[i] - RiskAvg[a];
RiskTrackBool[a] = 1;
j = i + 1;
do
{
if (Year[j] != Year[i])
{
break;
}
b = (int)Risk[j];
RiskTrack[b] = Loss[j] - RiskAvg[b];
RiskTrackBool[b] = 1;
j = j + 1;
} while (j < RowNo);
RowTrack = j;
//check through RiskTrack and if no entry set to 0 - avg
for (j = 0; j < RiskNo; j++)
{
if (RiskTrackBool[j] == 0)
{
RiskTrack[j] = -1.0 * RiskAvg[j];
RiskTrackBool[j] = 1;
}
}
//Now loop through and perform calcs
for (j = 0; j < RiskNo; j++)
{
//SD
RiskSD[j] = RiskSD[j] + RiskTrack[j] * RiskTrack[j];
//Covar
for (k = j + 1; k < RiskNo; k++)
{
Res[j][k] = Res[j][k] + RiskTrack[j] * RiskTrack[k];
}
}
//Reset RiskTrack
for (k = 0; k<RiskNo; k++)
{
RiskTrack[k] = 0.0;
RiskTrackBool[k] = 0;
}
i = RowTrack;
} while (i < RowNo);
//Account For Missing Years
MissingYears = NoSimYear - YearCount;
for (i = 0; i < RiskNo; i++)
{
//SD
RiskSD[i] = RiskSD[i] + MissingYears * RiskAvg[i] * RiskAvg[i];
//Covar
for (j = i + 1; j < RiskNo; j++)
{
Res[i][j] = Res[i][j] + MissingYears * RiskAvg[i] * RiskAvg[j];
}
}
//Covariance Matrix
for (i = 0; i < RiskNo; i++)
{
//SD
RiskSD[i] = sqrt(RiskSD[i] / (NoSimYear - 1));
if (RiskSD[i] == 0.0)
{
RiskSD[i] = 1.0;
}
//Covar
for (j = i + 1; j < RiskNo; j++)
{
Res[i][j] = Res[i][j] / (NoSimYear - 1);
}
}
//Correlation Matrix
for (i = 0; i < RiskNo; i++)
{
Res[i][i] = 1.0;
for (j = i + 1; j < RiskNo; j++)
{
Res[i][j] = Res[i][j] / (RiskSD[i] * RiskSD[j]);
}
}
//Clean up
delete[] RiskTrack;
delete[] RiskTrackBool;
delete[] RiskAvg;
delete[] RiskSD;
//Return Array
return Res;
}
Def File
LIBRARY CorrelLib
EXPORTS
CalcMatrix
VB.NET
I've created a simple winform with a button which triggers the code below. I wish to link to the dll, pass the arrays and receive the result as a 2d array.
Imports System
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("CorrelLib.dll", EntryPoint:="CalcMatrix", CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function CorrelMatrix2(ByRef Risk_FE As Integer, ByRef Year_FE As Integer, ByRef Loss_FE As Double, _
ByRef RowNo As Long, ByRef RiskNo As Long, ByRef NoSimYear As Long) As Double(,)
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer, j As Integer
Dim Risk() As Long, Year() As Long, Loss() As Double
Dim NoRisks As Long, NoSimYear As Long, NoRows As Long
Dim counter As Long
Dim Result(,) As Double
NoRisks = 50
NoSimYear = 10000
NoRows = NoRisks * NoSimYear
ReDim Risk(0 To NoRows - 1), Year(0 To NoRows - 1), Loss(0 To NoRows - 1)
counter = 0
For i = 1 To NoSimYear
For j = 1 To NoRisks
Risk(counter) = j
Year(counter) = i
Loss(counter) = CDbl(Math.Floor((1000000 - 1 + 1) * Rnd())) + 1
counter = counter + 1
Next j
Next i
Dim dllDirectory As String = "C:\Users\Documents\Visual Studio 2013\Projects\CorrelLibTestForm"
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + dllDirectory)
Result = CorrelMatrix2(Risk(1), Year(1), Loss(1), NoRows, NoRisks, NoSimYear)
End Sub
End Class
Current Error Message
An unhandled exception of type >'System.Runtime.InteropServices.MarshalDirectiveException' occurred in >CorrelLibTestForm.exe
Additional information: Cannot marshal 'return value': Invalid >managed/unmanaged type combination.
A double ** pointer to a pointer is not the same with a 2 dimension array in vb. Your best bet is to return just a pointer:
double *pdbl;
pdbl = &res[0][0];
return pdbl; //pdbl points to the first element
In vb you use an IntPtr to get the pointer:
Dim Result As IntPtr = Marshal.AllocHGlobal(4)
Dim dbl As Double
Result = CorrelMatrix2(Risk(1), Year(1), Loss(1), NoRows, NoRisks, NoSimYear)
//derefference the double pointer, i(integer) is actually the index in the array of doubles
dbl = CType(Marshal.PtrToStructure(IntPtr.Add(Result, i * 8), GetType(Double)), Double)
Your res array in c++ function needs to be public so the memory allocated to it is valid after the function returns.
I am trying to copy a 2d character array into another 2d character array using the string function strcpy but it's giving me the error of access violation. I don't know what is it that I am doing wrong. I am posting the code and error can somebody tell me what is it that I am doing wrong
int searching(char *name[],char * namesearched,int size)
{
int count =0;
int start = 0;
int end = count;
for(;start<=end;)
{
int mid = (start + end)/2;
if(strcmp(namesearched,name[mid])==0)
{
return mid;
}
else if(strcmp(namesearched,name[mid])==1)
{
end=mid -1;
}
else if(strcmp(namesearched,name[mid])==-1)
{
start = mid +1;
}
}
return -1;
}
void sorting(char **name,char ** meaning,int count)
{
for (int i=0;i<count;i++)
{
for(int j=i+1; j<count; j++)
{
char tempname[100];
char tempmeaning[100];
if(strcmp(name[j-1],name[j])>0)
{
strcpy(tempname,name[j]);
//strcpy(name[j],tempname);
strcpy(name[j-1],name[j]);
strcpy(name[j],name[j-1]);
strcpy(name[j-1],tempname);
strcpy(tempmeaning,meaning[j]);
strcpy(meaning[j],meaning[j-1]);
strcpy(meaning[j-1], tempmeaning);
}
}
}
}
void main()
{
int size=60;
int count=0;
char namesearched[100];
cout << "Enter the name to be searched: ";
cin.getline(namesearched , 100);
char** name= new char * [size];
char** meaning = new char * [size];
for(int i=0;i < size ; i++)
{
name[i]= new char [100];
meaning[i]= new char[100];
count ++;
}
name[0] = "Journalist";
name[1] = "Blister";
name[2] = "List";
name[3] = "Listen";
name[4] = "Novelist";
name[5] = "Song";
name[6] = "Eat";
name[7] = "West";
name[8] = "Idealist";
name[9] = "Industry";
name[10] = "Legalist";
name[11] = "Write";
name[12] = "Medal";
name[13] = "Nation";
name[14] = "Accident";
name[15] = "Nest";
name[16] = "Bird";
name[17] = "Animal";
name[18] = "Lion";//wrong
name[19] = "Pigeon";
name[20] = "Real";
name[21] = "Accept";
name[22] = "Ability";
name[23] = "Bald";
name[24] = "Backbite";
name[25] = "Wakeful";
name[26] = "Absolute";
name[27] = "Wail";
name[28] = "Abiding";
name[29] = "Unacceptable";
name[30] = "Tacker";
name[31] = "Vain";//wrong
name[32] = "Abolish";
name[33] = "Taking";
name[34] = "Unarmed";
name[35] = "Habit";
name[36] = "Notus";
name[37] = "Impecle";
name[38] = "Accelerate";
name[39] = "Agony";
name[40] = "Sulk";
name[41] = "Nowise";
name[42] = "Hypocrisy";
name[43] = "Nape";
name[44] = "Eccentric";
name[45] = "Naturally";
name[46] = "Gratitude";
name[47] = "Mesmerizing";
name[48] = "Epic";
name[49] = "Abstain";
name[50] = "Enactment";
name[51] = "Hammock";
name[52] = "Nodal";
name[53] = "Laborious";
name[54] = "Nonverbal";
name[55] = "Haggle";
name[56] = "Notorious";
name[57] = "Lagger";
name[58] = "Pathetic";
name[59] = "Norms";
meaning[0] = "Sahaafi";
meaning[1] = "Chaala";
meaning[2] = "Fehrist";
meaning[3] = "Sunna";
meaning[4] = "Naval Nigaar";
meaning[5] = "Ganna";
meaning[6] = "Khanna";
meaning[7] = "Maghrib";
meaning[8] = "Tadawuri";
meaning[9] = "Sannat";
meaning[10] = "Zabta Parast";
meaning[11] = "Likhna";
meaning[12] = "Tangha";
meaning[13] = "Qoom";
meaning[14] = "Hadsa";
meaning[15] = "Ghonsla";
meaning[16] = "Parinda";
meaning[17] = "Janwar";
meaning[18] = "Shair";
meaning[19] = "Kabootar";
meaning[20] = "Haqeekat";
meaning[21] = "Qabool";
meaning[22] = "Kabliyat";
meaning[23] = "Ganja";
meaning[24] = "Ghebat Karna";
meaning[25] = "Jagta";
meaning[26] = "Bikul";
meaning[27] = "Gham Karna";
meaning[28] = "Mustakil";
meaning[29] = "NaGawar";
meaning[30] = "Jorna Wala";
meaning[31] = "Gari";
meaning[32] = "Rad kar dena";
meaning[33] = "Dil-chasp";
meaning[34] = "Nehatta";
meaning[35] = "Addat";
meaning[36] = "Dakni hawwa";
meaning[37] = "Rokna";
meaning[38] = "Taiz karna";
meaning[39] = "Sakht Takleef";
meaning[40] = "Roth Jana";
meaning[41] = "Hargiz Nahi";
meaning[42] = "Naffaq";
meaning[43] = "Mankaa";
meaning[44] = "Sanki";
meaning[45] = "Fitratan";
meaning[46] = "Tashakur";
meaning[47] = "Mashoor Karna";
meaning[48] = "Razmiya";
meaning[49] = "Baaz Rakhna";
meaning[50] = "Nifaaz";
meaning[51] = "Jholay ki tarhan ka Bichona";
meaning[52] = "Gutheela";
meaning[53] = "Mehnat Talab";
meaning[54] = "Ghair Lafzey";
meaning[55] = "Takrar Karna";
meaning[56] = "Badnam";
meaning[57] = "Ahista Chalnay walla";
meaning[58] = "Intehai afsoos naak baat";
meaning[59] = "Mayar";
int mid;
sorting( name , meaning , count);
int mid = searching(name,namesearched,count);
if( mid == -1 )
{
char ** tempname = new char* [60];
char ** tempmeaning = new char*[60];
if(count == size)
{
int increase =(10 * size)/100;
size = increase + size;
for(int i=0 ; i<size ; i++)
{
tempname[i] = new char [100];
tempmeaning[i]= new char [100];
}
for(int i = 0; i<count ; i++)
{
strcpy(tempname[i],name[i]);
strcpy(tempmeaning[i],meaning[i]);
}
}
strcpy(tempname[count] , namesearched);
cin >> tempmeaning[count];
count ++;
sorting( tempname , tempmeaning , count);
for (int i =0;i < count ;i++)
{
delete [] name[i];
delete [] meaning[i];
}
//delete [] name;
//delete [] meaning;
name = tempmeaning;
meaning = tempmeaning;
tempmeaning = NULL ;
tempname = NULL;
}
else
{
cout <<"The meaning of " << namesearched << " is: " << meaning[mid] << endl;
}
_getch();
}
Access violation writing location 0x001fbe5c.
The value of count and size is 60
One thing more strcpy works on this line strcpy(tempname , name[j]) but when it encounter this line strcpy(name[j] , name[j-1]) it throws me the error of access violation
This function declaration
void sorting(char *name[],char *meaning[],int size,int count);
does not deal with two-dimensional arrays.
For example if you have two-dimensional arrays like this
char name[60][100];
char meaning[60][100];
then the function declaration will look like
void sorting( char name[60][100], char meaning[60][100], size_t count );
or
void sorting( char name[][100], char meaning[][100], size_t count );
or
void sorting( char ( *name )[100], char ( *meaning )[100], size_t count );
and the value of the argument for the third parameter should be equal to 60.
As for your function declaration then for example this parameter char *name[]
has type of incomplete one-dimensional array of pointers of type char * that is adjusted to type char **. And if the corresponding argument is an array of pointers to string literals then the function has undefined behavior because you may not change string literals.
So it seems you are processing the arrays incorrectly that is their definitions do not correspond to the logic of the function code.
Also parameter size is not used in the function.
Thus your code simply wrong initially.
Take into account that the condition in this if statement
if(strcmp(name[j-1],name[j]))
should look either like
if ( strcmp( name[j-1], name[j] ) > 0 )
if you want to sort the arrays in the ascending order or like
if ( strcmp( name[j-1], name[j] ) < 0 )
if you want to sort the arrays in the descending order.
EDIT: After you appended your question then it is seen that 1) there are memory leaks because the pointers that initially pointed to the allocated memory are reassigned with addresses of string literals and 2) you are trying to change string literals that are immutable.
Instead of for example
name[0] = "Journalist";
you have to write
strcpy( name[0], "Journalist" );
You don't need 2d char arrays, just array of strings. So you can do it without using strcpy. Something like:
void sorting(char *name[],char *meaning[], int count)
{
for (int i = 0; i < count; i++)
{
for(int j = 1; j < count - i; j++)
{
char *tempname;
char *tempmeaning;
if(strcmp(name[j-1],name[j]) > 0)
{
tempname = name[j];
name[j] = name[j-1];
name[j-1] = tempname;
tempmeaning = meaning[j];
meaning[j] = meaning[j-1];
meaning[j-1] = tempmeaning;
}
}
}
}
char *name[] is an array of pointers to char. Pointer to char can be interpreted like a pointer to the first element of array of chars (to string). So if you want to swap two strings in array, you just need to swap pointers to that strings.
So essentially with the libraries that i'm working with I cannot use std::string, as it uses a somewhat depreciated version of C++ I need to convert this xor function from using std::string to just using char or char *. I have been trying but I cannot figure out what I am doing wrong, as I get an error. Here is the code:
string encryptDecrypt(string toEncrypt) {
char key[] = "DSIHKGDSHIGOK$%#%45434etG34th8349ty"; //Any chars will work
string output = toEncrypt;
for (int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
If anyone could help me out, that would be great. I am unsure as to why I cannot do it by simply changing the strings to char *.
Edit:
What I have tried is:
char * encryptDecrypt(char * toEncrypt) {
char key[] = "DSIHKGDSHIGOK$%#%45434etG34th8349ty"; //Any chars will work
char * output = toEncrypt;
for (int i = 0; i < sizeof(toEncrypt); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
Please note I am not trying to convert an std::string to char, I simply cannot use std::string in any instance of this function. Therefore, my question is not answered. Please read my question more carefully before marking it answered...
The issue here is
char * output = toEncrypt;
This is making output point to toEncrypt which is not what you want to do. What you need to do is allocate a new char* and then copy the contents of toEncrypt into output
char * encryptDecrypt(char * toEncrypt) {
char key[] = "DSIHKGDSHIGOK$%#%45434etG34th8349ty"; //Any chars will work
int string_size = std::strlen(toEncrypt);
char * output = new char[string_size + 1]; // add one for the null byte
std::strcpy(output, toEncrypt); //copy toEncrypt into output
for (int i = 0; i < string_size; i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
Live Example
Since we are using dynamic memory allocation here we need to make sure that the caller deletes the memory when done otherwise it will be a memory leak.
sizeof() is a compile-time operator that evaluates the size of the type of its argument. When you do sizeof(toEncrypt), you're really just doing sizeof(char*) -- not the length of the string, which is what you want. You'll need to somehow indicate how long the toEncrypt string is. Here are two possible solutions:
Add an integer argument to encryptDecrypt specifying the length of toEncrypt in characters.
If you know that toEncrypt will never contain the null byte as a valid character for encryption / decryption (not sure of your application) and can assume that toEncrypt is null-terminated, you could use the strlen function to determine string length at runtime.
I'd recommend option 1, as strlen can introduce security holes if you're not careful, and also because it allows the use of null bytes within your string arguments.
What error are you getting? You can easily use a char* to do the same thing, I've included a sample program that verifies the functionality. This was built under VS2012.
#include <string>
#include <stdio.h>
std::string encryptDecrypt( std::string toEncrypt)
{
char key[] = "DSIHKGDSHIGOK$%#%45434etG34th8349ty"; //Any chars will work
std::string output = toEncrypt;
for (int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
void encryptDecrypt( char* toEncrypt )
{
char key[] = "DSIHKGDSHIGOK$%#%45434etG34th8349ty"; //Any chars will work
int len = strlen( toEncrypt );
for (int i = 0; i < len; i++)
toEncrypt[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
}
int main( int argc, char* argv[] )
{
const char* sample = "This is a sample string to process";
int len = strlen( sample );
char* p = new char[ len + 1 ];
p[len] = '\0';
strcpy( p, sample );
std::string output = encryptDecrypt( sample );
encryptDecrypt( p );
bool match = strcmp(output.c_str(), p) == 0;
printf( "The two encryption functions %smatch.\n", match ? "" : "do not " );
return 0;
}
Why not instead of string output = toEncrypt :
char *output = new char[std::strlen(toEncrypt) + 1];
std::strcpy(output, toEncrypt);
for(int y = 0; y < 5; y++)
{
char cst1[2] = {info[x+2], info[x+3]};
char cst2[2] = {info[x+5], info[x+6]};
sales[count][atoi(&info[x]) - 1] = atoi(cst1) + atoi(cst2);
x += 8;
}
Every time i do the following code the atoi(cst1) value is multiplied by two then added and atoi(cst2) is multiplied by 100 then added cant figure out why
cst1 and cst2 don't appear to be NUL-terminated.
char cst1[] = {info[x+2], info[x+3], '\0'};
char cst2[] = {info[x+5], info[x+6], '\0'};