I have the following c++ program that multiple 2 large numbers :
#include <iostream>
#include <string>
#define OVERFLOW 2
#define ROW b_len
#define COL a_len+b_len+OVERFLOW
using namespace std;
int getCarry(int num) {
int carry = 0;
if(num>=10) {
while(num!=0) {
carry = num %10;
num = num/10;
}
}
else carry = 0;
return carry;
}
int num(char a) {
return int(a)-48;
}
string mult(string a, string b) {
string ret;
int a_len = a.length();
int b_len = b.length();
int mat[ROW][COL];
for(int i =0; i<ROW; ++i) {
for(int j=0; j<COL; ++j) {
mat[i][j] = 0;
}
}
int carry=0, n,x=a_len-1,y=b_len-1;
for(int i=0; i<ROW; ++i) {
x=a_len-1;
carry = 0;
for(int j=(COL-1)-i; j>=0; --j) {
if((x>=0)&&(y>=0)) {
n = (num(a[x])*num(b[y]))+carry;
mat[i][j] = n%10;
carry = getCarry(n);
}
else if((x>=-1)&&(y>=-1)) mat[i][j] = carry;
x=x-1;
}
y=y-1;
}
carry = 0;
int sum_arr[COL];
for(int i =0; i<COL; ++i) sum_arr[i] = 0;
for(int i=0; i<ROW; ++i) {
for(int j=COL-1; j>=0; --j) {
sum_arr[j] += (mat[i][j]);
}
}
int temp;
for(int i=COL-1; i>=0; --i) {
sum_arr[i] += carry;
temp = sum_arr[i];
sum_arr[i] = sum_arr[i]%10;
carry = getCarry(temp);
}
for(int i=0; i<COL; ++i) {
ret.push_back(char(sum_arr[i]+48));
}
while(ret[0]=='0'){
ret = ret.substr(1,ret.length()-1);
}
return ret;
}
void printhuge(string a) {
cout<<"\n";
for(string::iterator i = a.begin(); i!=a.end(); ++i) {
cout<<*i;
}
}
int main() {
string a,b;
cin>>a>>b;
printhuge(mult(a,b));
return 0;
}
All is working fine, but I need to use char[] instead of "string" . I know it's silly but I have to use that format necessary. So - how can I convert the code to work with char[] definition ?
Any ideas is greatly appreciated, Thanks :)
Provided you don't need to modify the C string (the char array), i. e. it can be const char[] or const char *, use the c_str() method of std::string:
const char *c_string = str.c_str();
Edit: so your problem is that you should not use std::string at all. Well, in this case, this is how you can replace C++ strings with C strings:
C strings are 0-terminated arrays of char (or const char). As usually, in certain conditions, they decay into pointers.
You can get the length of a C string using the strlen() function in <string.h>.
To append strings to each other, use the strcat() or strncat() functions. Beware of buffer sizes and the extra space for the terminating NUL character!
etc.
Call std::string::c_str() on your string objects.
Just make sure the buffer isn't modifed by the functions.
Edit
Or, if you need to accept a char[], just create a string out of it.
Related
The code gets an exception of type out of range and i don't know why. It seems to work when i debug it, teh string is converted to what i want it to be.
First time on stack overflow btw:)
#include <iostream>
using namespace std;
string s;
string alpha = "abcdefghijklmnopqrstuvwxyz";
string crypto(string& s);
int main()
{
cin >> s;
cout << crypto(s);
return 0;
}
string crypto(string& s)
{
size_t i = 0;
while (i < s.length()) {
for (size_t j = 0; j < alpha.length(); j++) {
if (s.at(i) == alpha.at(j)) {
s.at(i) = alpha.at(alpha.length() - 1 - j);
++i;
}
}
}
return s;
}
Think about the case: if s.length() < alpha.length().
The problem was the i++ at the wrong place. You should format your code better, then this is much easier to spot.
Also avoid non-constant global variables and using namespace std:
#include <iostream>
#include <string> //Include the headers you use
const std::string alpha="abcdefghijklmnopqrstuvwxyz";
void crypto(std::string &s);
int main(){
std::string s;
crypto(s);
std::cout<<s;
return 0;
}
void crypto(std::string &s) //If you take the string by reference, it is changed, so you do not have to return it
{
for(std::size_t i = 0; i < s.length(); ++i) { //The for loop avoids the mistake completely
for(size_t j=0; j < alpha.length(); ++j){
if(s.at(i)==alpha.at(j)){
s.at(i)=alpha.at(alpha.length()-1-j);
}
}
}
}
To not solve your problem completely, there is still a bug in the code, that was also in yours. Try to find the error yourself.
The i++ was not put at the right place.
Moreover, there is another issue in the code: once an element has been replaced, you must leave the inner loop immediately (break). If not, you can have a -> z -> a in the same loop.
Input
abcyz
Output
zyxba
abcyz
#include <iostream>
#include <string>
std::string crypto(std::string& s) {
const std::string alpha = "abcdefghijklmnopqrstuvwxyz";
for (size_t i = 0; i < s.length(); ++i) {
for (size_t j = 0; j < alpha.length(); j++) {
if (s.at(i) == alpha.at(j)) {
s.at(i) = alpha.at(alpha.length() - 1 - j);
break;
}
}
}
return s;
}
int main() {
std::string s;
std::cin >> s;
std::cout << crypto(s) << std::endl;
std::cout << crypto(s) << std::endl;
return 0;
}
The inner loop of the crypto function can increment i past the end of the string. There's no test to stop it.
You could avoid this by breaking out of the loop when a letter is changed (that's more correct and potentially faster). That then means you should increment i outside the inner loop which means the outer loop can be a for loop as well.
string crypto(string &s) {
for (size_t i = 0; i < s.length(); ++i) {
for (size_t j = 0; j < alpha.length(); ++j) {
if (s.at(i) == alpha.at(j)) {
s.at(i) = alpha.at(alpha.length() - 1 - j);
break;
}
}
}
return s;
}
So I am trying so merge 2 sorted arrays into one and I get really weird numbers like an output. Here is my code:
#include<iostream>
using namespace std;
int* add(int first[],int second[], int sizeFirst, int sizeSecond)
{
int result[sizeFirst + sizeSecond];
int indexFirst = 0,indexSecond = 0;
for(int i = 0;i < sizeFirst + sizeSecond;i++)
{
if(indexFirst == sizeFirst || first[indexFirst] > second[indexSecond])
{
result[i] = second[indexSecond];
indexSecond++;
}
else
{
result[i] = first[indexFirst];
indexFirst++;
}
}
return result;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i = 0;i < n;i ++)
cin>>arr[i];
int m;
cin>>m;
int arr2[m];
for(int i = 0;i < m;i ++)
cin>>arr2[i];
int *res;
res = add(arr,arr2,n,m);
for(int i = 0;i < n + m;i ++)
cout<<res[i]<<" ";
return 0;
}
Notes: It sorts it properly, so the mistake is not there. Also I need to do it as a function because I will need it later on for some other stuff.
return result;
You are returning a pointer to local array, which gets destroyed immediately after - this is undefined behavior. You should either allocate it using new or use std::vector (which is preferred).
Also, int result[sizeFirst + sizeSecond]; is not valid C++ because the standard doesn't allow variable sized arrays (but int* result = new int[sizeFirst + sizeSecond]; is valid).
I need to read a txt file and store it into a matrix (we suppose that it'a a 2x2 matrix). I have a problem with the code below (I semplified it to be more cleat):
#include<stdexcept>
#include<string>
#include<fstream>
using namespace std;
class A{
private:
int **m;
void allocate_mem(int ***ptr){
*ptr = new int *[2];
(*ptr)[0] = new int[2*2];
for(unsigned i = 1; i < 2; i++)
(*ptr)[i] = (*ptr)[0] + i*2;
}
void read_file(string file_input){
ifstream fin(file_input.c_str());
allocate_mem(&m);
char a;
for(unsigned i = 0; i < 2; i++) {
for (unsigned j = 0; j < 2; j++) {
a = fin.get();
if(a=="X"){
//ISO C++ forbids comparison between pointer and integer [-fpermissive]
m[i][j] = 1;
}else{
m[i][j] = 0;
}
}
}
fin.close();
}
public:
A(){
throw logic_error("Error!");
}
A(string file_name){
read_file(file_name);
}
~A(){
delete[] m[0];
delete[] m;
}
};
input.txt
XX
X
I want to store a 2x2 matrix whose elemets are:
11
01
The solution is simple: Write C++ instead of C
Use standard containers instead of manual memory management.
Also, if you know the size of the data at compile-time, why do you use dynamic memory?
int m[2][2];
void read_file(const std::string& file_input) {
ifstream fin(file_input.c_str());
char a;
if( !fin ) throw;
for (std::size_t i = 0; i < 2; i++) {
for (std::size_t j = 0; j < 2; j++) {
a = fin.get();
if (a == 'X') { // '' is for characters, "" for strings. Thats why the compiler
m[i][j] = 1;// warns you (You are comparing the char[], which is decayed to
} else { // char*, with the integer value of the char variable)
m[i][j] = 0;
}
}
}
//Close not needed (RAII)
}
I have this code to do permutations of a string.
#include <iostream>
#include <string.h>
using namespace std;
/* Prototipo de función */
void Permutaciones(char *, int l=0);
void sort(string scadena[]);
//array global to copy all permutations and later sort
string array[900000];
int m=0;
int main() {
int casos;
cin>>casos;
char palabra[casos][13];
for(int i=0;i<casos;i++)
cin>>palabra[i];
for(int i=0;i<casos;i++){
m=0;
Permutaciones(palabra[i]);
sort(array);
}
sort(array);
system("pause");
return 0;
}
void sort(string scadena[]){
string temp;
for(int i=0;i<m;i++){
for(int j=i+1;j<m;j++){
if(scadena[i]>scadena[j]){
temp=scadena[i];
scadena[i]=scadena[j];
scadena[j]=temp;
}
}
}
for(int i=0;i<m;i++){
for(int j=1;j<m;j++){
if(scadena[i]==scadena[j] && j!=i){
for(int k=j;k <m; k++){
scadena[k]=scadena[k+1];
}
m--;
j--;
}
}
}
for(int i=0;i<m;i++){
cout<<scadena[i]<<endl;
}
}
void Permutaciones(char * cad, int l) {
char c; /* variable auxiliar para intercambio */
int i, j; /* variables para bucles */
int n = strlen(cad);
for(i = 0; i < n-l; i++) {
if(n-l > 2){
Permutaciones(cad, l+1);
}
else {
array[m]=cad;
m++;
}
/* Intercambio de posiciones */
c = cad[l];
cad[l] = cad[l+i+1];
cad[l+i+1] = c;
if(l+i == n-1) {
for(j = l; j < n; j++){
cad[j] = cad[j+1];
}
cad[n] = 0;
}
}
}
And the code generates all permutations fine, and later sorted the array and it works fine. But when i am intenting remove the repeated strings, the code show me somethings repeated, and not sorted.
Who can say me what is my error?
You could have accomplished it easier using standard library:
#include <algorithm>
using namespace std;
int main() {
int a[] = {1, 2, 5, 6, 7};
int n = 5;
do {
// print array a
} while (next_permutation(a, a + n));
}
Unless the task was to implement it on your own. And of course make sure your array is sorted before you try to permutate it in this way, otherwise you will miss some permutations.
HERE, is a simplest code for generating all combination/permutations of a given array without including some special libraries (only iostream.h and string are included) and without using some special namespaces than usual ( only namespace std is used).
void shuffle_string_algo( string ark )
{
//generating multi-dimentional array:
char** alpha = new char*[ark.length()];
for (int i = 0; i < ark.length(); i++)
alpha[i] = new char[ark.length()];
//populating given string combinations over multi-dimentional array
for (int i = 0; i < ark.length(); i++)
for (int j = 0; j < ark.length(); j++)
for (int n = 0; n < ark.length(); n++)
if( (j+n) <= 2 * (ark.length() -1) )
if( i == j-n)
alpha[i][j] = ark[n];
else if( (i-n)== j)
alpha[i][j] = ark[ ark.length() - n];
if(ark.length()>=2)
{
for(int i=0; i<ark.length() ; i++)
{
char* shuffle_this_also = new char(ark.length());
int j=0;
//storing first digit in golobal array ma
ma[v] = alpha[i][j];
//getting the remaning string
for (; j < ark.length(); j++)
if( (j+1)<ark.length())
shuffle_this_also[j] = alpha[i][j+1];
else
break;
shuffle_this_also[j]='\0';
//converting to string
string send_this(shuffle_this_also);
//checking if further combinations exist or not
if(send_this.length()>=2)
{
//review the logic to get the working idea of v++ and v--
v++;
shuffle_string_algo( send_this);
v--;
}
else
{
//if, further combinations are not possiable print these combinations
ma[v] = alpha[i][0];
ma[++v] = alpha[i][1];
ma[++v] = '\0';
v=v-2;
string disply(ma);
cout<<++permutaioning<<":\t"<<disply<<endl;
}
}
}
}
and main:
int main()
{
string a;
int ch;
do
{
system("CLS");
cout<<"PERMUNATING BY ARK's ALGORITH"<<endl;
cout<<"Enter string: ";
fflush(stdin);
getline(cin, a);
ma = new char[a.length()];
shuffle_string_algo(a);
cout<<"Do you want another Permutation?? (1/0): ";
cin>>ch;
} while (ch!=0);
return 0;
}
HOPE! it helps you! if you are having problem with understanding logic just comment below and i will edit.
I'm pretty new to C++ and I have some problems with getting into all that pointer stuff. Basically I am passing a pointer to a Function, creating an Array at that pointer. Back in the main function I can't access this array.
Here's my code:
#include <iostream>
using namespace std;
void createArray(char** dict, int* arraysize)
{
*arraysize = 26*26*26*26;
delete dict;
dict = 0;
//Initialisiere character array of character
//char **wortliste = 0;
dict = new char*[*arraysize];
for(int i = 0; i < *arraysize; i++)
dict[i] = new char[5];
int ctr = 0;
//Erstelle Einträge (sortiert)
for (char i = 'A'; i <= 'Z'; i++)
{
for (char j = 'A'; j <= 'Z'; j++)
{
for (char k = 'A'; k <= 'Z'; k++)
{
for (char l = 'A'; l <= 'Z'; l++)
{
dict[ctr][0] = i;
dict[ctr][1] = j;
dict[ctr][2] = k;
dict[ctr][3] = l;
dict[ctr][4] = '\0';
ctr++;
}
}
}
}
}
int main(void)
{
char** dict = 0;
int arraysize;
createArray(dict, &arraysize);
cout << dict[0] << endl << dict[arraysize-1] << endl;
return 0;
}
I can't figure out my error thank you very much in advance.
In C++ parameters are pass by value (unless explicitly marked as being reference parameters), so when you pass dict, a pointer (to a pointer to char) to createArray, the dict inside your function is a different object, albeit with the same initial value, as the dict in main. If you want to see changes to dict in main you would have to pass it by reference, or pass the address of it into a function taking a char ***.
E.g.
void createArray(char**& dict, int* arraysize)
or
void createArray(char*** pdict, int* arraysize)
{ // use (*pdict) instead of dict ...
and
// ...
createArray(&dict, &arraysize);
A more "C++" way to achieve what you want would be to have:
void createArray( std::vector<std::string>& dict );
and to simply have createArray resize the vector to the required size. Using standard containers like vector and string also frees you of the obligation to explicity deallocate that memory that you allocate which is currently missing from your code.
There are a couple of mistakes.
To delete an array:
char **array = /* new with whatever */;
/* do your work */
for (i = 0; i < array_size; ++i)
delete[] array[i];
delete[] array;
To new an array:
char **array = new char *[array_size];
for (i = 0; i < array_size; ++i)
array[i] = new char[array_size_2];
When deleteing, to make sure you don't iterate over a not-newed array, check it against NULL:
for (i = 0; i < array_size; ++i)
{
if (array[i] != NULL) /* Or simply if (array[i]) */
delete[] array[i];
array[i] = NULL;
}
if (array != NULL)
delete[] array;
array = NULL;
alternatively, since delete makes a check for NULL anyway, you can simplify this to:
if (array != NULL)
for (i = 0; i < array_size; ++i)
delete[] array[i]; /* no need to set to NULL after if going to delete the array */
delete[] array;
array = NULL;
Note: delete deletes a single object while delete[] deletes an array.
I can't imagine what you would do with such data, but you can at least use modern techniques.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> create() {
vector<string> result;
for (char i = 'A'; i <= 'Z'; ++i) {
for (char j = 'A'; j <= 'Z'; ++j) {
for (char k = 'A'; k <= 'Z'; ++k) {
for (char l = 'A'; l <= 'Z'; ++l) {
result.push_back(string() + i + j + k + l);
}
}
}
}
return result;
}
int main() {
vector<string> data = create();
cout << data.front() << endl << data.back() << endl;
}