簡體   English   中英

將 char** 轉換為 int C++

[英]Convert char** to int C++

所以我有一個符號數組,其中有另一個符號數組(如果我沒記錯的話)。 我需要做的是更改第三個元素( words[2] )。 這第三個元素肯定是一個數字。 我必須將這個數字增加 15%。 因此,我需要將words[2]轉換為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;
}

完整代碼:

#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;
}

它需要看起來像什么(第三個元素增加了 15%): 它需要看起來像什么

無法使用string執行此操作。 實際上,這是我大學的作業,不使用string是條件

您需要將char*轉換為int ,如下所示。 (int)鑄造不起作用

int a = atoi(words[2]); // make sure words[2] is null terminated

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM