Convert simple char to int ? (read from binary)

I have data.txt it contains

73167176


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
using namespace std;


int main()
{
	fstream fin;
	fin.open("data.txt",fstream::in);
	int k = 5;
	int product;
	char next;
	while(!fin.eof())
	{
		fin.get(next);
		//NEED CONVERSION
	}
	return 0;
}


next will firstly be '7' how to be 7 ??? Thanks !
make it int next instead of char next.

THen use fin >> next;
In
73167176
Will fin >> next reads the whole 73167176 ???

Can I use this to just get one number per time... '7', then '3', then '1' .... ?

with fin.get(next) and next is int ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <fstream>
#include <cctype>

// not for use with values which are not digits.
int to_int(char c)
{
     switch(c)
     {   //  makes no assumptions about character order
          case '0': return 0 ;
          case '1': return 1 ;
          case '2': return 2 ;
          case '3': return 3 ;
          case '4': return 4 ;
          case '5': return 5 ;
          case '6': return 6 ;
          case '7': return 7 ;
          case '8': return 8 ;
          case '9': return 9 ;
          default: return -1 ;
     }
}

int main()
{
     fstream fin("data.txt") ;

     char next ;
     while (fin.get(next) )
    {
          if ( std::isdigit(next) )
         {  
              int value = to_int(next) ;
              // do stuff with value.
         }
         else
         {
               std::cerr << "Non-digit found in input '" << next << "'\n" ;
               // handle error.
         }
    }
}
Last edited on
Char is already an integer, it is just interpreted/displayed as ASCII.

1
2
3
4
5
6
7
8
9
10
int x;
char ch;

while(!fin.eof())
{
	fin.get(next);
	//NEED CONVERSION               
        x =  next - '0';
       
}


Or you can just leave characters as is:

1
2
3
char value01 = '1', value02 = '2';

cout << value01 << " + " << value02 << " = " << static_cast<int> (value01 - '0' + value02 - '0');



Edit: This isn't binary btw.
Last edited on
Sure this very simple i think this will work.


int atoi(const char ) ; it convert char to int


1
2
3
4
5
6
while(!fin.eof())
	{
		fin.get(next);
		int atoi(next);
		
	}
Topic archived. No new replies allowed.