1

I want to convert from char to integer, following is the code-

FILE *p; char temp; int temp_int; p=fopen("week3data","r"); temp=getc(p); temp_int=atoi(temp) 

number in file goes from 1 to 200, need some guidance.

3
  • 2
    Convert a single digit character, or convert a string containing a full three-digit number? Commented Aug 18, 2015 at 8:57
  • 1
    What is the question exactly? Also pretty sure this is a duplicate... Commented Aug 18, 2015 at 8:59
  • 3
    And are you sure you're programing in C++ and not C? There's no explicit C++ functionality in the code you show, only old C. Commented Aug 18, 2015 at 8:59

2 Answers 2

1

If you're using C++, please use C++ SL:

std::fstream stream("file.txt", std::ios_base::in); float number; stream >> number; std::cout << number; 

Edit: Don't forget to check if your stream is valid:

if (!stream) { throw std::runtime_error("Cannot open file"); } 
Sign up to request clarification or add additional context in comments.

Comments

0

If you're reading from a file, you shouldnt be using

temp=getc(p); 

and if you use

temp=fgetc(p); 

and the number is, for example 200, you will only read the "2".

so the answer is:

better use

char * buffer; fgets(buffer,10, p); temp_int=atoi(buffer); 

6 Comments

bufffer, not temp. Also what if the number is 10000000001? :)
That buffer looks a bit too uninitialized to be honest.
Actually buffer size 10 will do... Sorry
@Akalikin thanks for showing the mistake, it was buffer not temp. He said the numer goes between 1 and 200... so obviously with buffer size 10 its far enough... but what if number is 1000000000000? well this would be out of his problem.
@Quentin : im not giving him the whole code of course, i just gave him what he needed to reach the answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.