hi ^^..
i have another question ,, it may sound stupid but what should i do , i'm just a beginner ^^..

if i am reading a digit from a file as a char. and then i want to read it again as an int.as an int. with other digits. Can i use.. can i use (putback()) member function? and how that will be?

can u please put an example ^^ ....
:)

Recommended Answers

All 10 Replies

Yes, you can use putback:

#include <iostream>

int main()
{
  char ch;
  int i;

  std::cin.get ( ch );
  std::cout<<"You read "<< ch <<'\n';
  std::cin.putback( ch );
  std::cin>> i;
  std::cout<<"You read "<< i <<'\n';
}

But if you start to use anything more complicated than just this, it would be a good idea to read the whole line as a string and do conversions in memory.

does i = ch in your example?

ch is the first digit of i. Isn't that what meant by "reading a digit from a file as a char. and then i want to read it again as an int.as an int. with other digits"?

yeah that what i meant , but i've tried it n' it didnt work ,, that why i asked( -_-!),,

>but i've tried it n' it didnt work
This isn't useful information. How did you try it, how didn't it work? This is the result I get:

12345
You read 1
You read 12345

And I'm reasonably sure that I'm doing everything correctly. So chances are you're doing something wrong, but you need to describe what you're doing (with code examples) so that I can tell you what.

mm ok , thax for the help ,, i'll go n' check my program(now i know that the problem with my program isnt with putback) ^^ ..

>now i know that the problem with my program isnt with putback
When you're learning a new technique which you want to incorporate in your program, it's advisable to create a separate test program which does something similar to what you plan to attempt with your original program. Doing this isolates any errors you might have, and merging the two programs is trivial.

maybe a dumb question, but why use putback() at all? Why not just use the seek functions to move the file pointer to where-ever you want it? I would suspect putback() just calls seek to move the file pointer back one char in the buffer.

>maybe a dumb question, but why use putback() at all?
I'm guessing that he only needs to put back one character, and a direct seek is more complicated and less transparent.

seek function? =_=!
i didnt took this one yet! maybe in the next course ,, this is my first course in C++ ^^..
anyway thnx for helping me ^^

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.