removing namespace std specifically sprintf in a denary to hex C++ program - c++

I have coded a denary to hex converter and am trying to find a way to remove the sprinf built in function as well as the stoi built in function that i used because as i am using c++ more i am told that using namespace std is bad practice but i cannot think of a way of doing this without breaking my program any help would be appreciated.
also i have left my comments in my code for future Questions should i remove these or leave them in when posting thankyou
#include <iostream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
int DecToHex(int Value) //this is my function
{
char *CharRes = new (char); //crestes the variable CharRes as a new char
//sprintf is part of the standard library
sprintf(CharRes, "%X", Value);
//char res is the place the concerted format will go
//value is the value i want to convert
//%X outputs a hex number
//snprintf covers the formatting of a string
int intResult = stoi(CharRes); //stoi is a function in the library
std::cout << intResult << std::endl; //print int results to the screen
return intResult; //returns int result
}
int main()
{
int a;
std::cout << "Please enter a number" << std::endl;
std::cin >> a; //stores the value of a
DecToHex(a); //runs the function
system("pause"); //pauses the system
return 0; //closes the program
}

Stream in C++ already have built in function for converting format like decimal /hexa etc .. so you can just do this :
int main()
{
int a;
std::cout << "Please enter a number" << std::endl;
std::cin >> a; //stores the value of a
std::cout << std::hex; // Set the formating to hexadecimal
std::cout << a; // Put your variable in the stream
std::cout << std::dec;, // Return the format to decimal. If you want to keep the hexa format you don't havr to do this
std::cout << std::endl; // Append end line and flush the stream
/* This is strictly equivalent to : */
std::cout << std::hex << a << std::dec << std::endl;
system("pause"); //pauses the system
return 0; //closes the program
}
Using std::hex in the stream will print the value in hexa. Using std::dec will print the value in decimal format. Using std::octa will print the value in octal format.
You can call any function from the standard library without using using namespace std simply by prefixing the function with std::.
For example, std::snprintf, std::stoi etc..

Related

Returning and Printing Strings in C++

I am trying to get a file path from the user in the getPath() function and return the path as a string. I am having trouble because the compiler says i need to use const char's and i dont know how to do that. How would I use const chars and what even are they. Also how do I print them to the console like in the main function.
#include <iostream>
#include <stdio.h>
#include <string.h>
char getPath() {
char path[64];
std::cout << "Input File Name For Debugging:";
gets(path);
std::cout << "Debugging: ";
puts(path);
return path[64];
}
int main(){
char path[64];
int pathlen = strlen(reinterpret_cast<const char *>(path));
//suppost to print the char array
for(int i; i < pathlen; i++){
std::cout << path[i];
}
return 0;
}
Lot's of misunderstandings
1) char is not a string, it's a character
2) An array of chars (e.g. char [64]) is not a string, its an array. It can hold a string but that's a subtly different idea
3) You don't use [64] when you mean the whole array, so return path[64]; is not the correct way to return a string.
4) Don't mix C++ I/O (std::cin, std::cout) with C I/O (puts, gets), it doesn't work reliably, Stick with C++ I/O so
std::cout << "Debugging: " << path << '\n';
not
std::cout << "Debugging: ";
puts(path);
5) You never call your getPath function so of course it doesn't execute
6) You don't initialise your loop variable i in your final loop so it has no predictable value. You should initialise i to 0
for(int i; i < pathlen; i++){
std::cout << path[i];
should be
for(int i = 0; i < pathlen; i++){
std::cout << path[i];
As you can see lots and lots of mistakes for a very short program. I'm going to show two different correct ways to write this program.
So there are two ways to represent a string in C++, there's the C++ way and there's the way that C++ inherits from C. The code you are writing above is trying to do things the C way, so I'll show that first, but actually the C++ way is much much easier. I'll show that second, but it's the way you should do things.
The first way is to use an array of characters to hold the string. But arrays have serious problems in C++. In particular it's not possible to return an array from a function, so your code above was never going to work, even if you'd fixed all the smaller problems. The way you get C++ to 'return' an array is a bit curious and I'm not going to explain it properly (you need to read a good C++ book). What you do is declare the array in the calling function and pass the array as a parameter. Here's your program written using this technique (and fixed of all the other problems).
#include <iostream>
void getPath(char path[], int n) {
std::cout << "Input File Name For Debugging:";
std::cin.getline(path, n);
std::cout << "Debugging: " << path << '\n';
}
int main(){
char path[64];
getPath(path, 64);
std::cout << path << '\n';
return 0;
}
Note I'm using getline to read the string, which is one C++ way to read a string. getline requires that you pass the size of the array it's going to read into, so I've passed that to getPath as well as the array itself.
Now for the easy way. C++ has it's own string type called std::string. You don't need to use tricky arrays at all. And the C++ string type can be returned from a function in the normal way. This makes for much more natural code. To use the C++ string type all you need to do is #include <string>. Here's your program rewritten to use the C++ string type
#include <iostream>
#include <string>
std::string getPath() {
std::cout << "Input File Name For Debugging:";
std::string path;
std::getline(std::cin, path);
std::cout << "Debugging: " << path << '\n';
return path;
}
int main(){
std::string path;
path = getPath();
std::cout << path << '\n';
return 0;
}
Notice this second program is closer to your original code, getPath has a return type, only it's std::string not char, and it has a return statement to return the path. This is the way you should be writing this code, the C++ string type will make writing string code much easier for you.

Inserting and extracting numeric_limits<T>::infinity in a stream

The following program apparently shows an inconsistency when writing and reading on a std::stringstream a double set to "infinity", using std::numeric_limits<double>::infinity.
#include <string>
#include <sstream>
#include <iostream>
#include <limits>
#include <iterator>
int main() {
std::stringstream stream;
double d;
// Part 1
d=4;
stream << d << " ";
d=std::numeric_limits<double>::infinity();
stream << d << " ";
d=5;
stream << d;
stream.seekg(std::ios_base::beg);
std::string s = stream.str();
std::cout << "string : " << s << std::endl;
// Part 2
std::cout << "Extraction of data 1:" << std::endl;
stream.seekp(std::ios_base::beg);
stream >> d;
std::cout << d << std::endl;
stream >> d;
std::cout << d << std::endl;
stream >> d;
std::cout << d << std::endl;
// Part 3
std::cout << "Extraction of data 2:" << std::endl;
std::istringstream stream2(s);
std::istream_iterator<double> iter(stream2);
std::istream_iterator<double> eos;
while (iter != eos)
{
std::cout << (*iter) << std::endl;
iter++;
}
return 0;
}
See it live.
The output is
string : 4 inf 5
Extraction of data 1:
4
0
0
Extraction of data 2:
4
In part 1 a double "infinity" is written to a stringstream and the string extracted from it shows an "inf" corresponding to such an infinity.
In part 2, however, the substring "inf" is apparently extracted to 0. Moreover, the stream appears to be in a bad state, since successive extractions give again 0.
Similarly, in part 3 a istream_iterator is used to extract the doubles from the string. The iterator reaches an end-of-stream before reading "inf".
Obviously, one could easily fix the problem by extracting words instead of double and converting each of them to a "normal" double, or to std::numeric_limits<double>::infinity when a "inf" is encountered. However, this seems like reinventing the wheel, given that the standard library already contains a lot of code to extract data from a stream....
Why is there a difference when inserting and extracting a std::numeric_limits<double>::infinity?
Within the standard library, is there a possibility of extracting a double which could also be infinity, without resorting to write a function that extracts words and convert them to double?
Additional note
According to the c++ reference, std::stod and similar functions already convert "inf" to an infinite expression. Hence, it looks like std::stringstream::operator<< does not use std::stod or similar to convert a piece of string to a double.

Print one (float) decimal using cout

I have a float number and I want to print one digit after decimal. How can I do this using cout? I have tried the following code but its giving wrong display.
#include <iostream>
using namespace std;
int main()
{
float time = 2.2;
cout.precision(1);
cout << time << endl;
return 0;
}
You need to set tge precision to one and float formatting flags to fixed:
std::cout << std::fixed << std::setprecision(1);
BTW, don't use std::endl. To get a newline use '\n' and if you really mean to flush the stream use std::flush.

C++ Confusion. Reading Integer From Text File. Convert to ASCII

I am learning C++ for the first time. I have no previous programming background.
In the book I have I saw this example.
#include <iostream>
using::cout;
using::endl;
int main()
{
int x = 5;
char y = char(x);
cout << x << endl;
cout << y << endl;
return 0;
}
The example makes sense: print an integer and the ASCII representation of it.
Now, I created a text file with these values.
48
49
50
51
55
56
75
I am writing a program to read this text file -- "theFile.txt" -- and want to convert these numbers to the ASCII value.
Here is the code I wrote.
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
int main()
{
ifstream thestream;
thestream.open("theFile.txt");
char thecharacter;
while (thestream.get(thecharacter))
{
int theinteger = int(thecharacter);
char thechar = char(theinteger);
cout << theinteger << "\t" << thechar << endl;
}
system ("PAUSE");
return 0;
}
This is my understanding about the second program shown.
The compiler does not know the exact data type that is contained in "theFile.txt". As a result, I need to specify it so I choose to read the data as a char.
I read the each digit in the file as a char and converted it to an integer value and stored it in "theinteger".
Since I have an integer in "theinteger" I want to print it out as a character but char thechar = char(theinteger); does not work as intended.
What am I doing incorrect?
You are reading char by char, but you really (I think) want to read each sequence of digits as an integer. Change your loop to:
int theinteger;
while (thestream >> theinteger )
{
char thechar = char(theinteger);
cout << thechar << endl;
}
+1 For a very nicely formatted & expressed first question, BTW!
You are reading one char at a time from the file. Hence, if your file contains:
2424
You will first read the char "2" from the file, convert it to an int, and then back to a char, which will print "2" on cout. Next round will print "4", and so on.
If you want to read the numbers as full numbers, you need to do something like:
int theinteger;
thestream >> theinteger;
cout << char(theinteger) << endl;

Check variable type in C++

So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
Safe C++ Way
You can define a function for this using std::istringstream:
#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
// always keep the scope of variables as close as possible. we see
// 'd' only within the following block.
{
double d;
ss >> d;
}
/* eat up trailing whitespace if there was a double read, and ensure
* there is no character left. the eof bit is set in the case that
* `std::ws` tried to read beyond the stream. */
return (ss && (ss >> std::ws).eof());
}
To assist you in figuring out what it does (some points are simplified):
Creation of a input-stringstream initialized with the string given
Reading a double value out of it using operator>>. This means skipping whitespace and trying to read a double.
If no double could be read, as in abc the stream sets the fail-bit. Note that cases like 3abc will succeed and will not set the fail-bit.
If the fail-bit is set, ss evaluates to a zero value, which means false.
If an double was read, we skip trailing whitespace. If we then are at the end of the stream (note that eof() will return true if we tried to read past the end. std::ws does exactly that), eof will return true. Note this check makes sure that 3abc will not pass our check.
If both cases, right and left of the && evaluate to true, we return true to the caller, signaling the given string is a double.
Similar, you check for int and other types. If you know how to work with templates, you know how to generalize this for other types as well. Incidentally, this is exactly what boost::lexical_cast provides to you. Check it out: http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm.
C Way One
This way has advantages (being fast) but also major disadvantages (can't generalized using a template, need to work with raw pointers):
#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str()) // skip trailing whitespace
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
strtod will set endptr to the last character processed. Which is in our case the terminating null character. If no conversion was performed, endptr is set to the value of the string given to strtod.
C Way Two
One might thing that std::sscanf does the trick. But it's easy to oversee something. Here is the correct way to do it:
#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
std::sscanf will return the items converted. Although the Standard specifies that %n is not included in that count, several sources contradict each other. It's the best to compare >= to get it right (see the manpage of sscanf). n will be set to the amount of the processed characters. It is compared to the size of the string. The space between the two format specifiers accounts for optional trailing whitespace.
Conclusion
If you are a beginner, read into std::stringstream and do it the C++ way. Best not mess with pointers until you feel good with the general concept of C++.
There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
double cube(double n);
int main()
{
while(true)
{
cout << "Enter the number you want to cube: ";
string user;
cin >> user;
try
{
// The following instruction tries to parse a double from the 'user' string.
// If the parsing fails, it raises an exception of type bad_lexical_cast.
// If an exception is raised within a try{ } block, the execution proceeds
// with one of the following catch() blocks
double d = lexical_cast <double> (user);
cout << "The cube of " << d << " is " << cube(d) << "." << endl;
break;
}
catch(bad_lexical_cast &e)
{
// This code is executed if the lexical_cast raised an exception; We
// put an error message and continue with the loop
cout << "The inserted string was not a valid double!" << endl;
}
}
return 0;
}
double cube (double n)
{
return n*n*n;
}
sscanf can do what you want; it returns the number of arguments properly processed. This should get you started:
//cubes a user entered number
#include <iostream>
#include <cstdio>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
string user;
cin >> user; //user entering the number
// Convert the number to a double.
double value;
if(sscanf(user.c_str(), "%lf", &value) != 1)
{
cout << "Bad! " << user << " isn't a number!" << endl;
return 1;
}
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Other methods posted in other answers have their advantages and disadvantages. This one has issues with trailing characters and isn't "C++"-y.
I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
You can fall back on C and use strtod
You program reads in a string and then passes it to a function that attempts to convert the string into double.
bool is_double(const char* strIn, double& dblOut) {
char* lastConvert = NULL;
double d = strtod(strIn, &lastConvert);
if(lastConvert == strIn){
return false;
} else {
dblOut = d;
return true;
}
}