簡體   English   中英

在 C++ 中使用 atoi 將 char 數組轉換為 int 值

[英]Converting a char array to an int value by using atoi in C++

我對 C++ 中的編碼非常陌生,我現在面臨一個問題。 我需要編寫一個 function 接收 DD.MM.YYYY 格式的生日(字符串)作為參數。 然后我需要提取日期、月份和年份,並使用 atoi() function 將它們保存在一個 int 數組中。 我的代碼中的問題是,當我使用 atoi 獲取日期和月份時,我得到了 0 作為值,但是在嘗試將年份作為 int 值時,我得到了正確的值。 誰能告訴我我做錯了什么?

謝謝

#include <iostream>
#include <cstdlib>

using std::cout, std::cin, std::string;

int * extractDate(string birthday)  //Birthday format: DD.MM.YYYY
{
    // Extraction of DD
    char dayArr[2] = {birthday[0], birthday[1]};
    dayArr[2] = '\0';
    // Extraction of MM
    char monthArr[2] = {birthday[3], birthday[4]};
    monthArr[2] = '\0';
    // Extraction of YYYY
    char yearArr[4] = {birthday[6], birthday[7], birthday[8], birthday[9]};
    yearArr[4] = '\0';
    // Int-Array to save the data as numbers
    int * birthdayArr = new int[3];

    // Converting and saving the data to integers
    birthdayArr[0] = atoi(dayArr);    // Here I get 0
    birthdayArr[1] = atoi(monthArr);  // Here I get 0 as well
    birthdayArr[2] = atoi(yearArr);   // Here I get the year correctly
    birthdayArr[3] = '\0';

    return birthdayArr;
}

您需要聲明足夠大的 arrays 以容納 null 終結器。 您正在 arrays 之外寫入 null 字節。

    char dayArr[3] = {birthday[0], birthday[1], '\0'};

其他兩個 arrays 也是如此。

當您嘗試將它們的最后一個元素設置為“\ 0”時,您正在編寫 arrays 的末尾。 由於 dayArr 的長度為 2,它的有效索引只有 0 和 1——當您嘗試寫入 dayArr[2] 時,您實際上是在寫入 memory 中的任何內容,這(通常)是下一個變量您在 function 中聲明。

如果您將 arrays 的大小每個增加 1,它們應該可以工作。

暫無
暫無

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

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