converting part of string to int and back creates random character [duplicate] - c++

This question already has answers here:
Convert char to int in C and C++
(14 answers)
Closed 2 years ago.
I am having trouble trying to converting time from 12 hour format to 24 hour format.
Note:- This is from an online test site and is filled with boilerplate code to work with the site, so I'm only going to post the part of the program where I am allowed to type.
string timeConversion(string s) {
/*
* Write your code here.
*/
int hours = ((int) s[0])*10+((int) s[1]);
char r[7];
//cout<< sizeof(s)<<"\n";
if(s[8]=='P')
{
hours=hours+12;
r[0]=(char) (hours/10);
r[1]=(char) (hours%10);
for (int i=2;i<8;i++)
{
r[i]=s[i];
}
}else
{
for(int i=0;i<8;i++)
{
r[i]=s[i];
}
}
return r;
}
Here is the input and outputs of test
Input(stdin):-
07:05:45PM
My output(stdout):-
6:05:45
Expected output:-
19:05:45
Now I test line 5 (i.e the line where i convert the hours section into an integer) in another compiler by itself and for some reason instead of properly converting its showing hours=534
Can you guys tell me what went wrong and how to fix it?

I found out what was going wrong with my code earlier. The reason why it didnt work is because c++ doesn't convert the numerical character into the actual numerical value, rather it converts it into the corresponding ascii value for which starts at 48 for "0" and ends at 57 for "9"
Statement to use for converting hours in the string and vice versa would be to
string -> int
int hours = (((int) s[0])%48)*10+(((int) s[1])%48);
or
int hours = (((int) s[0])-48)*10+(((int) s[1])-48);
int -> string
r[0]=(char) ((hours/10)+48);
r[1]=(char) ((hours%10)+48);

Related

weird when use atof in Visual Studio [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
When I used VS 2015 to debug the following code,
int main()
{
char thev[8] = "0.12345";
float fv = atof(thev);
printf("%f\n", fv);
return 0;
}
the value of fv in watch window is 0.12345004,
and printf is 0.123450, how to let fv=0.12345 in the run time?
There is similar post, here, but no answer there, can somebody help me?
And I pasted that code to my VS 2015,
int main()
{
const char *val = "73.31";
std::stringstream ss;
ss << val;
double doubleVal = 0.0f;
ss >> doubleVal;
}
the value doubleVal in watch window is 73.310000000000002
Replace the following code:
printf("%f\n", fv);
with:
printf("%.5f\n", fv);
Explaination:
we use a width (%.5f) to say that we want 5 digits (positions) reserved for the output.
The result is that 5 “space characters” are placed before printing the character. And the next character will be not printed.
Reference: https://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
There is no exact representation in IEEE single precision for 0.12345. The closest two values on either side of it are 0.123450003564357757568359375 and 0.12344999611377716064453125. atof is picking the former, I think because it is closer to 0.12345 than the latter.

c++ How to convert String to int (ascii code to value); [duplicate]

This question already has answers here:
How to convert a single char into an int [duplicate]
(11 answers)
Closed 5 years ago.
i have been trying to make a program that checks if a national identification number is valid how ever i have run into a issue and i can't find an answer anywhere.
I am using a string to store the users input of the identification code and i need to somehow covert the string to int keeping the symbol instead of getting an ascii value.
Example:
(lets say the user inputs the string persKods as 111199-11111
the 5th symbol is 9 so the year value should output as 9 instead of 54 which is its ascii value)
int day,month,year;
year=this->persKods.at(4);
cout << year; // it outputs 54 instead of 9 :/
Can you try to ascci value of '0'.
#include <iostream>
using namespace std;
int main() {
// your code goes here
string str="111199";
int test = str.at(4) - '0';
cout<<test;
return 0;
}
For more information link

Sum of char and int leads to weird char in my c++ code

I tried searching for a solution online but I could not find one. The closet I came is this A similar unanswered question on cplusplus.com
Here is my code....
int main()
{
char a[1000000],s[100000];
scanf("%s",s);
int i,l=strlen(s);
//cout<<l;
for(int i=0;i<l;i++)
a[i]=s[l-i-1]; //to reverse the word in s[]
cout<<a<<endl;
for(i=0;i<l;i++)
{
s[i]+=a[i]-96;
if(s[i]>'z')
{
int diff=s[i]-'z';
s[i]='a'+(diff-1);
}
}
cout<<s;
return 0;
}
//l=length of string.
//a[i]=is another string with word in s[] being reversed.
My problem is that when I execute this and give an input , say, world it prints some weird characters.
I am unable to see any fault in the logic I applied and I feel frustrated now.
The question asked was that I am supposed to add two strings one of which is reversed version of the other one and that the addition is to be performed in such a way that 'a' + 'b' = 'c' , 'd' + 'a' = 'e' .... and 'z' + 'a' = 'a'. So that the addition is closed under small-alphabets.
Your problem is that you're using a signed char (a signed byte). When the signed char goes over 127, then it flips negative. This causes your computation to miss the fact that the value is out of range, and when it's printed it's converted back to a high character.
You can simply replace your wrap around check with this:
while ((unsigned char)s[i] > 'z')
{
s[i] -= 26;
}
And then your program at least does what you wanted it to do. There are good suggestions in the comments for making it more robust as well.

String to Integer Conversion in MFC [duplicate]

This question already has answers here:
Convert MFC CString to integer
(12 answers)
Closed 7 years ago.
I am just a beginner to MFC platform. I am just trying a simple pgm. Getting 2 numbers in 2 edit boxes and displaying the sum in the third edit box when a button is clicked.
This is my code:
void CMineDlg::OnEnChangeNumber1()
{
CString strNum1,strNum2;
m_Number1.GetWindowText(strNum1,10); //m_NUmber1 is variable to 1st edit box.
m_Number2.GetWindowText(strNum2,10); //m_Number2 is variable to 2nd edit box.
}
void CMineDlg::OnBnClickedSum()
{
m_Result=m_Number1+m_Number2;
}
I know I have to convert the strings to integer. But I have no idea how to do it. Pls Help.
You can use Class Wizard to add variables of integer type and associate them with edit boxes. Then, in OnEnChangeNumber1 event handler (or in OnBnClickedSum), you simply call UpdateData(TRUE); which causes those variables to update their values. After that, you can sum those integer variables.
Use
CString strNum = _T("11"); //CString variable
int num; //Integer Variable
_stscanf(strNum, _T("%d"), &num); //Conversion
Or
num = atoi((char*)(LPCTSTR)strNum);
The correct UNICODE compliant way of doing this:
CString str = _T("10");
int nVal = _ttoi(str);
__int64 = _ttoi64(str);

How to effectively assign numerical string values to integers? [duplicate]

This question already has answers here:
C++ Converting a time string to seconds from the epoch
(10 answers)
Closed 9 years ago.
I have a string containing a value of time in HH:MM:SS(':' are a part of the string.) format.I have to convert the time into seconds and give that value to an integer variable.I am not aware of any function that can help me do it.
Use sscanf_s.
For example:
void ScanTime(char* strTime)
{
int hours;
int minutes;
int seconds;
sscanf_s(strTime, "%d:%d:%d", &hours, &minutes, &seconds);
printf("hours: %d\nminutes:%d\nseconds:%d\n", hours, minutes, seconds);
}
int _tmain(int argc, _TCHAR* argv[])
{
ScanTime("13:57:44");
return 0;
}
Since this is not a standard C++ function it greatly depends on what framework or library you are using.
This how it's done in Borland C++ Builder:
String Time;
Time = "12:34:56";
TDateTime DT;
try{
DT = StrToTime(Time);
}catch(...){String M = "Error converting time string: "+Time; Application->MessageBox(M.c_str(),"ERROR",MB_OK );}
Use strtol.
for example::
int a=(int)strtol(numeric_string.c_str(),(char **)NULL,10);
if your intension isto simply convert HH:MM:SS, you need to write a function
algorithm would be like(assuming 24Hr format):
split the string using ":"
Convert each part using strtol to integer.
last part+(60* middle part)+(60*60*firstpart) will give you the
actual value