You are here:

C++/Command-line

Advertisement


Question
Hello. I am new at C and C++, but I do program Windows Batch files. Is there a way to make a C program (GUI not necessary) that would take a number and truncate it past the decimal?

IE: Let's call said program "round.exe"

(Hope you can read batch scripts; I know that isn't your specialty)

@echo off
round.exe 52.36541>test.txt
type test.txt
pause
exit

When ran, the new batch file would accept "52.36541" and output "52"

Any help that you can be would be great.

Answer
The basic idea would be to:

- ensure you use the form of main that has command line argument parameters argc and argv
 (argument count and argument values)
- ensure there are two arguments (the command name - e.g. round.exe and the value to round)
- extract the second argument (argv[1]) as a floating point value
- round it to an integer
- write it to stdout

Hence we start with:

   #include <iostream>
   
   int main( int argc, char* argv[] )
   {
       if ( argc != 2 )
       {
         std::cerr << "Usage:\n"
         "    round decimal-value\n\n"
         " where:\n"
         "    decimal-value is a decimal number such as 52.36541"
         << std::endl
         ;
         return 1;
       }

   // ...
       
   }

To extract the decimal argument value we read it using the C++ formatted input using a C++ std::istringstream:

   #include <iostream>
   #include <sstream>
       
   // main from above up to ... comment, which can be replaced with:

       double decimal_value(0.0);
       std::istringstream in_str(argv[1]);
       in_str >> decimal_value;
       if ( ! in_str.good() )
       {
         std::cerr << "Error : expected decicmal value as command argument."
         << std::endl
         ;          
         return 1;
       }

   // ...

We can round the value in various ways, the most obvious is to add 0.5 to the value and convert to an integer - however note that not all typical 64-bit double values will fit into a typical 32 bit integer, because of this you might get a warning about loss of data or similar from the compiler:

       int rounded_value( decimal_value + 0.5 );

We can then write it out to stdout, called std::cout in C++:

       std::cout << rounded_value << std::endl;

Note that I am using  ISO standard C++ - so a fairly up to date compiler (late 1990s or later).

The full code is shown below:

   #include <iostream>
   #include <sstream>
   
   int main( int argc, char* argv[] )
   {
       if ( argc != 2 )
       {
         std::cerr << "Usage:\n"
         "    round decimal-value\n\n"
         " where:\n"
         "    decimal-value is a decimal number such as 52.36541"
         << std::endl
         ;
         return 1;
       }

       double decimal_value(0.0);
       std::istringstream in_str(argv[1]);
       in_str >> decimal_value;
       if ( ! in_str.good() )
       {
         std::cerr << "Error : expected decicmal value as command argument."
         << std::endl
         ;
         return 1;
       }
       
       int rounded_value( decimal_value + 0.5 );
       std::cout << rounded_value << std::endl;
   }

You might like to look at:

   - floating point functions such as ceil and floor
   - non standard functions such as rint available with some systems / compilers
   - various ways that rounding can be expressed
   - formatting numeric output - e.g. to ensure a floating point value is written with
     no digits after the decimal point so it looks like an integer
     (hint: check out the iomanip header and the stream format flags and flag member functions
      such as setf)
     e.g. #include <iomanip> at the start of the program and replace:

         int rounded_value( decimal_value + 0.5 );
         std::cout << rounded_value << std::endl;

       with:
         std::cout << std::fixed << std::setprecision(0)
         << decimal_value+0.5 << std::endl;  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.