Convert a int digit to a char (example: from 1 to '1') - visual-c++

I'd like to convert a int digit to a char (no to convert from ascii code). I'd like to convert it from int type to char type. (Example: from 5 to '5') Is it possible?

Use:
int x = 5; char c = '0' + x; // c == '5'

Related

Arduino String to float

I'm trying to convert a string of HEX to a single float value. The string is 4 bytes long. It was defined as:
String B = "";
It is a substring of a longer string:
B = input.substring(6,14);
This results in the string I am trying to convert in to a single float value.
Online I found following code:
float y = *(float*)&B;
This compiles without an error, but when I run the code it's always 0.000000. I'm guessing I can't use that function with a string. A typical string can be "bb319ba6" which should be -0.002710083. For that I'm using a IEEE 754 converter I found online.
I basically need to do the same conversion on the Arduino. I hope somebody can help me with that.
You really shouldn't use String on these limited-RAM Arduinos. It can cause weird errors and hangs after random amounts of time (more info here). Just use a character array to hold the characters received from the sensor. Here's some code that will work with either String or a char[]:
uint8_t fromHex( char c )
{
if ((0 <= c) && (c <= '9'))
return (c - '0');
if ('A' <= c) && (c <= 'F'))
return (c - 'A');
if ('a' <= c) && (c <= 'f'))
return (c - 'a');
return 0; // not a hex digit
}
void foo()
{
float y;
uint8_t *yPtr = (uint8_t *) &y; // a pointer the the 4 bytes of `y`
for (uint8_t i=0; i<sizeof(y); i++) {
*yptr = fromHex( B[ 6+2*i ] ) << 4;
*yptr++ = fromHex( B[ 6+2*i + 1] );
}
...
It simply stores the 4 bytes into the float, since Arduino floats already use the IEEE 754 format. No need to decode the exponent, mantissa, etc.

Replacing and deleting a character from a string in c++?

This program is giving wrong output,, basically i want to remove the character specified and replace it by 'g'...For e.g: All that glitters is not gold if the user entered o then the output should be All that glitters is ngt ggld but the program is deleting all the characters from n onwards
#include <iostream>
using namespace std;
int main()
{
string input(" ALL GLItters are not gold");
char a;
cin>>a;
for(int i=0;i<input.size();i++)
{
if(input.at(i)==a)
{
input.erase(i,i+1);
input.insert(i,"g");
}
}
cout<<"\n";
cout<<input;
}
string& erase (size_t pos = 0, size_t len = npos);
The second parameter ( len ) is the Number of characters to erase.
You have to put 1 not i+1 :
input.erase(i,1);
http://www.cplusplus.com/reference/string/string/erase/
Why not replace it directly? Replace your for loop with this:
for (char& c : input)
{
if (c == a)
c = 'g';
}
Live example here.

Multiple ints to const char*

I'm trying to make as string out of multiple ints.
Let's say:
int year = 1995;
int month = 12;
int day = 18;
const char* date = ("%d-%d-%d", month, day, year);
I get:
error: invalid conversion from 'int' to 'const char*' [-fpermissive]
What's the best way to go about this?
First, convert your parameters to strings with std::to_string().
string m = std::to_string(month);
string d = std::to_string(day);
string y = std::to_string(year);
Then, concatenate them:
string datestr = m + d + y;
Finally, convert that string into a char const*, using c_str(), which converts a string int to a C-like string.
char const* date = date.c_str();

What is optimal algorithm to make all possible combinations of a string?

I find other similar question too complicated.
I think it means if we are given pot then combinations will be
pot
opt
top
pot
pto
pot
so I wrote the following code:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char s[10];
char temp;
cin>>s;
char t[10];
for(int i=0;i<3;i++)
{
for(int j=i;j<3;j++)
{
strcpy(t,s);
temp=s[i];
s[i]=s[j];
s[j]=temp;
cout<<s<<"\n";
strcpy(s,t);
}
}
Is there a better way ?
This problem is inherently an O(N!) (factorial) complexity problem. The reason is that for each position of each potential word, there will be a decrementing amount of possibilities of characters that can fill the position, An example with 4 letters a, b, c, and d.
-----------------
Positions: | 0 | 1 | 2 | 3 |
-----------------
In position 0, there are 4 possibilities, a, b, c, or d
Lets fill with a
-----------------
String: | a | | | |
-----------------
Now Position 1 has 3 possibilities of fill letters b, c, or d
Lets fill with b
-----------------
String: | a | b | | |
-----------------
Now Position 2 has 2 possibilities of fill letters c, or d
Lets fill with c
-----------------
String: | a | b | c | |
-----------------
Now Position 1 has only 1 possibility for a fill letter: d
-----------------
String: | a | b | c | d |
-----------------
This is only for 1 string, the complexity comes from (in this case) the potential possibilities that can fill a character location for a given output word, thus:
4 * 3 * 2 * 1 = 4!
This can be extended to any amount of input letters and is exactly N! if there are no repeat letters. This also represents the AMOUNT OF WORDS you should result with.
Code to perform something like this could be (TESTED AND WORKING IN C):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
void printPermutations(int level, const char * inString, char * outString){
unsigned int len = strlen(inString);
char * unusedLetter;
int j;
if( 1 == len ){
printf("%s%s\n", outString, inString);
}else{
unusedLetters = (char *)malloc(sizeof(char) * (len - 1));
for(int startLetter = 0; startLetter < len; startLetter++){
outString[level] = inString[startLetter];
// setup the "rest of string" string
j = 0;
for(int i = 0; i < len; i++){
if( i != startLetter ){
unusedLetter[j] = inString[i];
j++;
}
}
// recursive call to THIS routine
printPermutations(level+1, unusedLetters, outString);
}
}
}
int main(int argc, char * argv[]){
unsigned int len;
char * outString;
if(argc != 2) return 0;
len = strlen(argv[1]);
outString = (char *)malloc(sizeof(char) * (len + 1));
outstring[len] = '\0';
printPermutations(0, argv[1], outString);
return 0;
}
From outside, call this as follows:
projectName abc
sample output from using "abc"
abc
acb
bac
bca
cab
cba
If there are repeat letters lets say a, a, b, c
then there will ALWAYS be repeat words.
With these cases, the amount of UNIQUE result words should be the amount of unique characters factorial, so for the above case it would be 3! not 4!.
The reason for this is that it does not matter WHICH of the a's fills a given spot and thus the uniqueness is given be the amount of unique letters provided. This is also a hard problem, and in ways I would say you should generate ALL N! words first, then run a second algorithm to search for the repeat words and delete. There may be smarter ways of generating the unique words on the fly.
The following solution is O(N!).This takes repetitions into account too :
#include<stdio.h>
void permute(char s[10],char *p);
int count=0;
main(){
char s[10];
int i;
scanf("%s",s);
permute(s,s);
}
//takes into account repetetion
void permute(char s[10],char *p){
char *swap,temp;
if(*(p+1)==0) {
count++;
printf("%4d] %s\n",count,s);
}
else{
for(swap=p;*swap;++swap){
char *same;
for(same=p;*same!=*swap;++same){};
if(same==swap){
temp=*swap;
*swap=*p;
*p=temp;
permute(s,p+1);
*p=*swap;/*restoring the original string*/
*swap=temp;
}
}
}
}

stick integer to string and char*

How can I add an integer variable to a string and char* variable? for example:
int a = 5;
string St1 = "Book", St2;
char *Ch1 = "Note", Ch2;
St2 = St1 + a --> Book5
Ch2 = Ch1 + a --> Note5
Thanks
The C++ way of doing this is:
std::stringstream temp;
temp << St1 << a;
std::string St2 = temp.str();
You can also do the same thing with Ch1:
std::stringstream temp;
temp << Ch1 << a;
char* Ch2 = new char[temp.str().length() + 1];
strcpy(Ch2, temp.str().c_str());
for char* you need to create another variable that is long enough for both, for instance. You can 'fix' the length of the output string to remove the chance of overrunning the end of the string. If you do that, be careful to make this large enough to hold the whole number, otherwise you might find that book+50 and book+502 both come out as book+50 (truncation).
Here's how to manually calculate the amount of memory required. This is most efficient but error-prone.
int a = 5;
char* ch1 = "Book";
int intVarSize = 11; // assumes 32-bit integer, in decimal, with possible leading -
int newStringLen = strlen(ch1) + intVarSize + 1; // 1 for the null terminator
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
snprintf(ch2, intVarSize, "%s%i", ch1, a);
ch2 now contains the combined text.
Alternatively, and slightly less tricky and also prettier (but less efficient) you can also do a 'trial run' of printf to get the required length:
int a = 5;
char* ch1 = "Book";
// do a trial run of snprintf with max length set to zero - this returns the number of bytes printed, but does not include the one byte null terminator (so add 1)
int newStringLen = 1 + snprintf(0, 0, "%s%i", ch1, a);
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
// do the actual printf with real parameters.
snprintf(ch2, newStringLen, "%s%i", ch1, a);
if your platform includes asprintf, then this is a lot easier, since asprintf automatically allocates the correct amount of memory for your new string.
int a = 5;
char* ch1 = "Book";
char* ch2;
asprintf(ch2, "%s%i", ch1, a);
ch2 now contains the combined text.
c++ is much less fiddly, but I'll leave that to others to describe.
You need to create another string large enough to hold the original string followed by the number (i.e. append the character corresponding to each digit of the number to this new string).
Try this out:
char *tmp = new char [ stelen(original) ];
itoa(integer,intString,10);
output = strcat(tmp,intString);
//use output string
delete [] tmp;

Resources