Reputation: 43
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.
Upvotes: 1
Views: 87
Reputation: 37
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);
Upvotes: 0
Reputation: 1433
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");
}
Upvotes: 1