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

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

Related

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

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);

Why does the replica work replace in c++? [duplicate]

This question already has answers here:
Replace part of a string with another string
(17 answers)
Closed 2 years ago.
I started learning C ++ and my task is to replace some characters in the text. Something similar to the template Here are some examples:
<h1>Title</h1>$ js $<p>text...</p>
result:
<h1>Title</h1> </script>alert(1)</script> <p>text...</p>
I tried to do it with this code, but nothing worked:
#include <iostream>
#include <string>
using namespace std;
int main(){
string text = "<h1>Title</h1>$ js $<p>text...</p>";
string js_code = " </script>alert(1)</script> ";
string result = text.replace(text.find("$ js $"), js_code.length(), js_code);
cout << result << endl;
return 0;
}
result:
<h1>Title</h1> </script>alert(1)</script>
The text was inserted into the line, but everything after this text disappeared. Also, sometimes I will use Russian characters, and they are in UTF-8 encoding. 1 Symbol weighs more.
The second parameter of std::string::replace(size_type pos, size_type count, const basic_string& str); is the
length of the substring that is going to be replaced
e.g. how many characters should be removed after pos and before inserting str. You want to replace just 6 characters. Your code should look like this:
std::string pattern = "$ js $";
std::string result = text.replace(text.find(pattern), pattern.length(), js_code);
On another note you should check if find returns a valid index before using it.

String.length() shows incorrect value [duplicate]

This question already has answers here:
Read whole ASCII file into C++ std::string [duplicate]
(9 answers)
Closed 3 years ago.
I am trying this following code in cpp
#include <iostream>
#include <string>
void Strlength(const string& s) {
cout << s.length() << endl;
}
int main() {
string s;
cin >> s;
cout << s.length() << endl;
Strlength(s);
return 0;
}
The string which I am giving as input is 100,000 characters long and is like "xxxxxxx...xxxxabcde"(fill the ... with remaining x)
This gives me the output as
4095
4095
I am expecting the output to be 100000. what am I doing wrong?
This relates to one of the hackerrank problem (Test case 10): String Similarity
Assuming you describe the input correctly, that is it is one single "word", then the issue is not in your code. The issue must be in the environment which runs the code. It has some kind of mechanism to feed the standard input to your program. Either that has a limitation on total input length, or it has a limitation of line length. 4 kilobytes is 4096 bytes, so perhaps your input is limited by that: 4095 chars of the word plus a newline character (or terminating 0 byte of string, or whatever).
If you are running this under some kind of web interface in browser, the problem could even be, that the input field in the web page has that limitation.
If you need to dig into this, try to read char by char and see what you get, how many chars and how many newlines. Also examine cin.fail(), cin.eof(), cin.bad() and cin.good(). For the question code, you should expect failbit to be false, and eofbit might be true oe false depending on how the input was truncated.

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

Assigning variables while ignoring symbols? (c++) [duplicate]

This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 9 years ago.
I was wondering how you would assign multiple variables from a single line of user input if it contained symbols. Such as, if the user input was 5-25-1995, is it possible to assign 5, 25, and 1995 to different variables and ignore the "-"'s? I have been trying to use cin.ignore(), but haven't had any luck as of yet.
Thanks.
Short version:
user inputs "3-24-1995"
desired outcome
int month is 3,
int day is 24,
int year is 25,
char dummy;
int month, day, year;
cin >> month >> dummy >> day >> dummy >> year;
As your specific requirement was that the input be in the form "3-24-1995", therefore
may be something along the lines will comply with your needs and produce what you wanted.
/* Code */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char str[] ="3-24-1995"; // Your input that you will have some way of getting
char * month, *day, *year;
month=strtok (str,"-");
day = strtok (NULL,"-");
year = strtok (NULL,"-");
// Here, converting to int, just because you were looking to convert it into
// int otherwise you could just leave it un converted too.
printf("month: %d day: %d year: %d\n",atoi(month), atoi(day), atoi(year));
}