中易网

C++中能从字符型数据中提取整型数据吗?

答案:5  悬赏:40  
解决时间 2021-04-27 05:10
  • 提问者网友:说不出醉人情话
  • 2021-04-26 21:16
如果我有一个字符型数据"123",能提取出整型数据123吗?能的话怎么编程?
最佳答案
  • 二级知识专家网友:承载所有颓废
  • 2021-04-26 22:10

有强制转换的啊


char a


(int)a或者int(a)试试

全部回答
  • 1楼网友:桃花别处起长歌
  • 2021-04-27 02:35

#include<iostream>

#include<stdlib.h>

using namespace::std;

void main()

{

    char* a = "123";

    int b[3] = atoi(a);

    for(int i = 0;i<3;i++)

    {

    cout<<a[i]<<"\t";

    }

}

那个atoi()在哪个头文件我不太确定,你查下   

  • 2楼网友:随心随缘不随便
  • 2021-04-27 01:11
用sstream,sscanf或者atoi,推荐用sstream。我给你写个山寨版的lexical_cast #include <iostream> #include <sstream> using namespace std; template <class dest, class src> dest lexical_cast(src s) {     static stringstream sstrm;     sstrm.clear();     sstrm << s;     dest t;     sstrm >> t;     return t; } int main() {     int a = lexical_cast<int>("123");     double b = lexical_cast<double>("123.456");     cout << a << endl;     cout << b << endl; }
  • 3楼网友:深街酒徒
  • 2021-04-26 23:32
当然可以 用atoi("123")就可以了。
  • 4楼网友:猎杀温柔
  • 2021-04-26 22:36
#include <stdio.h> #include <assert.h> int myfun(char *str){     int i = 0,n = 0,flag = 1;     if(str[0] == '-')         i = 1;flag = -1;     for(; str[i] != '\0' ; i++){         assert(str[i] >= '0' && str[i] <= '9');         n = str[i] - '0' + n*10;     }     return n*flag; } int main(int argc, char *argv[]) {     int a;     char str[] = "1024";     a = myfun(str);     printf("%d\n",a);     return 0; } 本文来自CSDN博客,转载请标明出处: http://blog.csdn.net/alien73/archive/2008/12/08/3477033.aspx
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息