如何在C ++中读取文件时从字符转换为整数? [英] How to convert from character to integer in reading a file in C++?

查看:69
本文介绍了如何在C ++中读取文件时从字符转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中我有一个文件aa.txt,其中的数字是以01234的形式写的,我正在使用get()逐个字符地读取这个文件,但是我想把所有数字都放在整数中在temp中形成,但它无法转换为01234,它分配为48 49 50 51 52。如何将它们从字符转换为整数?



我尝试过的方法:



In the below program i have a file aa.txt which is having the numbers written in the form of 01234 and i am reading this file character by character using get() , but i want to put all the numbers in the integer form in temp but it is not able to convert as 01234 , it is assigning as 48 49 50 51 52 . How can i convert them from character to integer?

What I have tried:

int main()
{
    ifstream f;

    int sum=0;
    int temp[5];
    f.open("E://aa.txt",ios::in);

    char c;
    int num[5];
    char num2[5];
    int j=0;
    while(!f.eof())
    {
        c=f.get();
        cout<<c<<" ";
        num[j]=c;
        j++;
    }


    for(int i=0;i<5;i++)
    {
        num2[i]=num[i];
        temp[i]=(int)num2[i];
        cout<<temp[i]<<" ";
    }
}

推荐答案

请参阅此处:将字符串解析为整数C ++ - Google搜索 [ ^ ]


这篇关于如何在C ++中读取文件时从字符转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆