Reputation: 25
So I have an array of symbols which has another array of symbols in it (if i'm not wrong). What I need to do is to change third element (words[2]
). This third element will definitely be a number. I have to increase this number by 15 percent. Therefore, I need to convert words[2]
to int
?
Function:
void create(char* str) {
char** words = new char* [strlen(str)];
int count = 0;
for (char* part = strtok(str, " "); part != NULL; part = strtok(NULL, " ")) {
words[count] = _strdup(part);
count++;
}
cout << "\nNew sentence with edited values:" << endl;
words[2] = words[2] + ((int)words[2] / 100) * 15; //the main problem as I guess
for (int i = 0; i < count; i++) {
printf("%s ", words[i]);
}
cout << endl;
delete[] words;
}
Full code:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <string.h>
using namespace std;
void create(char*);
void main() {
const int maxLength = 100;
char* str = new char[maxLength];
cout << "Enter sentence:\n";
cin.getline(str, maxLength);
create(str);
delete[] str;
}
void create(char* str) {
char** words = new char* [strlen(str)];
int count = 0;
for (char* part = strtok(str, " "); part != NULL; part = strtok(NULL, " ")) {
words[count] = _strdup(part);
count++;
}
cout << "\nNew sentence with edited values:" << endl;
words[2] = words[2] + ((int)words[2] / 100) * 15;
for (int i = 0; i < count; i++) {
printf("%s ", words[i]);
}
cout << endl;
delete[] words;
}
What it needs to look like (3rd element increased by 15 percent):
Cannot do this using string
. Actually, it is my homework from a university and not using string
is the condition
Upvotes: 0
Views: 3971
Reputation: 2954
you need to convert a char*
to int
like below. (int)
casting won't work
int a = atoi(words[2]); // make sure words[2] is null terminated
Upvotes: 1