c++ - 如何从字符数组中提取数字字符串成员

标签 c++ arrays casting

我想提取字符数组的数字字符串值。实际上我想提取文件名中嵌入的数字以进行某些文件管理。例如,如果有一个文件名 file21 ,那么我想要该文件名中的十进制数 21

如何提取这些值?

我尝试了以下操作,但结果是意外的值。我认为这是在进行算术运算时从 char 到 int 的隐式类型转换的结果。

char * fname;
cout<<"enter file name";
cin>>fname;

int filenum=fname[4]%10+fname[5];
cout<<"file number is"<<filenum;

注意: 文件名严格采用fileXX格式,XX是01到99之间的数字

最佳答案

您需要减去'0'才能得到数字字符的十进制值:

int filenum=(fname[4]-'0')*10+(fname[5]-'0');

更好的是,您应该使用atoi:

int filenum = atoi(fname+4);

关于c++ - 如何从字符数组中提取数字字符串成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485529/

相关文章:

c# - 将 struct* 从 c# 传递到 c++ dll

c++ - boost program_options 中的链接错误

c++ - 当我对共享库使用 "stripped, with debug_info"命令时, "file"是什么意思?

c - & 在 c 中的代码行为的输出

python - np.partition() 如何解释参数 kth?

c++ - 不一致造成的static_cast困惑

c++ - 常见的 C++ 实现如何处理 static_cast 和 reinterpret_cast

c++ - 为什么 `std::set::erase(const key_type&)` 返回 `size_type` 而不是 `bool` ?

swift - CLLocationCoordinate2D 不符合预期的字典值类型 'AnyObject'

python - 展开数组并附加行名称