[英]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.