Subj : Re: directly inputting numbers To : borland.public.cpp.borlandcpp From : "Michael Fruchter" Date : Thu Jul 17 2003 12:45 pm How will the program know where the number ends? I'm dealing with a text that has many numbers that are not delimited (e.g. by spaces) but are of fixed width. I was hoping that it's possible to specify the amount of characters that you want to read into your integer (analogous to fgets with strings). maeder@glue.ch (Thomas Maeder [TeamB]) wrote: >"Michael Fruchter" writes: > >> Is there a way to directly input a number from a non-delimited text as >> opposed to reading in a certain amount of characters using "fgets" and >> converting to an integer using "atoi" (and then, if necessary, dividing >> by 10^x for x decimal places)? > >You can use the Standard C++ iostream functionality, e.g.: > >#include >#include >#include > >int main() >{ > int i; > if (std::cin >> i) > { > ; // do something useful with i > return EXIT_SUCCESS; > } > else > { > std::cerr << "input failure\n"; > return EXIT_FAILURE; > } >} > >You can read values of other numerical types by simply substituting them for >int. If you have the text in a string already, you can use a >std::istringstream or a std::istrstream instead. > > >[Note that what I wrote above is ISO Standard C++ syntax. Even the latest >release of Borland C++ predates this standard by years. While the functionality >is supported, you will probably have to adjust the syntax a bit to make >Borland C++ accept this code.] .