Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

Convert char** to int C++

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 << "
New 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:
";
    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 << "
New 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): What it needs to look like

Cannot do this using string. Actually, it is my homework from a university and not using string is the condition


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...