C++: Convert string or char to int [duplicate] - c++

This question already has answers here:
How can I convert a std::string to int?
(24 answers)
Closed 2 years ago.
If I have:
string number = "45";
How do I turn "45" into 45 as an integer?
I want to be able to do this:
string number + 20 = 65

You can use the following example from https://en.cppreference.com/w/cpp/string/basic_string/stol:
#include <iostream>
#include <string>
int main()
{
std::string str1 = "45";
std::string str2 = "3.14159";
std::string str3 = "31337 with words";
std::string str4 = "words and 2";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
// error: 'std::invalid_argument'
// int myint4 = std::stoi(str4);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}

Related

Wrong knowledge of pointers [duplicate]

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Why does cout print char arrays differently from other arrays?
(4 answers)
Closed 2 years ago.
Currently, I'm trying to understand why I have to use:
std::cout << "&str1:" << &str1 << std::endl;
To get the memory address of:
const char * str1 = "Good Morning";
I expected that:
std::cout << "str1:" << str1 << std::endl;
would do so.
Here is an example:
void charPointerExamples() {
const int * myInt = new int(1);
const char * str1 = "Good Morning";
const char * str2 = str1;
std::cout << "myInt:" << myInt << std::endl;
std::cout << "&str1:" << &str1 << std::endl;
std::cout << "&str2:" << &str2 << std::endl;
std::cout << "str1:" << str1 << std::endl;
std::cout << "str2:" << str2 << std::endl;
std::cout << "*str1:" << *str1 << std::endl;
std::cout << "*str2:" << *str2 << std::endl;
delete myInt;
}
The output itself:
myInt:0081D450
&str1:003CFD20
&str2:003CFD14
str1:Good Morning
str2:Good Morning
*str1:G
*str2:G

String constructor with a int is not printed

1. string s6 {0};
2. string s5 {'a','b',7};
cout << "S6 ::: " << s6 << endl;
cout << "S5 ::: " << s5 << endl;
Expect undefined behaviour 'nullptr' but does print an empty string.
Prints ab not expected behaviour.
Running on QT5.. compiler clang on MacOs
In the both cases
1. string s6 {0};
2. string s5 {'a','b',7};
there is used the constructor that accepts an initializer list.
In the second case the integer literal 7 can be represented in the type char. So there is no narrowing conversion.
Consider the following program.
#include <iostream>
#include <string>
int main()
{
std::string s6 {0};
std::string s5 {'a','b',7};
std::cout << s6.size() << ": ";
for ( char c : s6 ) std::cout << static_cast<int>( c ) << ' ';
std::cout << '\n';
std::cout << s5.size() << ": ";
for ( char c : s5 ) std::cout << static_cast<int>( c ) << ' ';
std::cout << '\n';
return 0;
}
Its output is
1: 0
3: 97 98 7

String Functions: Strcat()

I'm currently writing a program that uses string functions. I need some advice/hints on how I can display "Hello World" and its length with myStrcat() in main(). I'm new to programming and any support would be greatly appreciated.
My Code:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int myStrlen(char str1[])
{
int i = 0;
for (i=0; str1[i] != '\0'; i++)
str1[i] = '\0';
return i;
}
int myStrcat(char str2[], char str3[])
{
}
int myStrcpy(char str4[], char str5[])
{
int i = 0;
for (i=0; str5[i] != '\0'; i++)
str4[i] = str5[i];
str4[i] = '\0';
return i;
}
int main()
{
const int SIZE = 11;
char s1[SIZE] = "Hello";
char s2[SIZE] = "World";
cout << "s1: " << " " << s1 << endl << endl; ///Should display "Hello"
cout << "The length of s1: " << myStrlen(s1) << endl << endl;
cout << "Doing strcat(s1, s2) " << endl;
myStrcat(s1, s2);
cout << "s1: " << " " << s1 << endl; /// Should display "Hello World"
cout << "The length of s1: " << myStrlen(s1) << endl << endl;
cout << "Doing strcpy(s1, s2) " << endl;
myStrcpy(s1, s2);
cout << "s1: " << " " << s1 << endl; /// Should display "World"
cout << "The length of s1: " << myStrlen(s1) << endl << endl;
My Output:
s1: Hello
The length of s1: 5
Doing strcat(s1, s2)
s1:
The length of s1: 0
Doing strcpy(s1, s2)
s1: World
The length of s1: 5
Line 6 and 7 are suppose to display Hello World and its length (which is 11).
You have a number of not just quite right beginning to each of your functions. Firstly, let's think about the returns for each. myStrlen should return size_t instead of int. C++ designates a size_type for counters, measuring, etc.. The remaining functions should return char* (or nullptr on failure).
Looking at your myStrlen function where you have
for (i=0; str1[i] != '\0'; i++)
str1[i] = '\0';
You are setting every character in str1 to the nul-character because you are applying the loop to the next expression. You should not be worrying about nul-terminating anything within myStrlen -- you are just counting characters. So you can rewrite it as follows:
size_t myStrlen (const char *str)
{
size_t l = 0;
for (; str[l]; l++) {}
return l;
}
Your myStrcpy looks workable, though you should always validate your input parameters are not nullptr before using them -- I leave that to you. Since you have a myStrlen function, you can simply use that along with memcpy to create your myStrcpy function as:
char *myStrcpy (char *dest, const char *src)
{
size_t len = myStrlen(src);
return (char *)memcpy (dest, src, len + 1);
}
(note: traditionally you have source (src) and destination (dest) parameters when copying or concatenating)
For your myStrcat function, you are just using the myStrlen function to find the offset in dest to append src, so you really just need a call to myStrlen and then a call to myStrcpy to copy src to that offset in dest, e.g.
char *myStrcat (char *dest, const char *src)
{
size_t len = myStrlen (dest);
return myStrcpy (dest + len, src);
}
In your main(), if you want a space between "Hello" and "World", then const int SIZE = 11; is one too-low to hold the concatenated string "Hello World" which would require 12-bytes (including the nul-terminating character). Do Not Skimp on buffer size. 128 is plenty small.
Remaining with your main() but updating SIZE = 12; and adding a space between "Hello" and "World" with an additional call to myStrcat, you could do the following:
int main (void)
{
const int SIZE = 12; /* too short by 1 if you add space between */
char s1[SIZE] = "Hello";
char s2[SIZE] = "World";
std::cout << "s1: " << " " << s1 << std::endl << std::endl;
std::cout << "The length of s1: " << myStrlen(s1) << std::endl << std::endl;
std::cout << "Doing strcat(s1, s2) " << std::endl;
myStrcat(s1, " ");
myStrcat(s1, s2);
std::cout << "s1: " << " " << s1 << std::endl;
std::cout << "The length of s1: " << myStrlen(s1) << std::endl << std::endl;
std::cout << "Doing strcpy(s1, s2) " << std::endl;
myStrcpy(s1, s2);
std::cout << "s1: " << " " << s1 << std::endl;
std::cout << "The length of s1: " << myStrlen(s1) << std::endl << std::endl;
}
(note: don't include using namespace std;, it is just bad form in this day and age)
Example Use/Output
$./bin/mystrcpy
s1: Hello
The length of s1: 5
Doing strcat(s1, s2)
s1: Hello World
The length of s1: 11
Doing strcpy(s1, s2)
s1: World
The length of s1: 5
Look things over and let me know if you have further questions.
First you should read Why is “using namespace std;” considered bad practice?
Don't use c style strings if you are starting programming. Use std::string. It's much simpler to use.
#include <iostream>
#include <string>
int myStrlen(const std::string &str) {
return str.length();
}
int myStrcat(std::string &str1, const std::string &str2) {
str1 += str2;
str1.length();
}
int myStrcpy(std::string &str1, const std::string &str2) {
str1 = str2;
return str1.length();
}
int main() {
std::string s1 = "Hello";
std::string s2 = "World";
std::cout << "s1: " << s1 << "\n\n"; ///Should display "Hello"
std::cout << "The length of s1: " << myStrlen(s1) << "\n\n";
std::cout << "Doing strcat(s1, s2) " << '\n';
myStrcat(s1, s2);
std::cout << "s1: " << s1 << '\n'; /// Should display "Hello World"
std::cout << "The length of s1: " << myStrlen(s1) << "\n\n";
std::cout << "Doing strcpy(s1, s2) " << '\n';
myStrcpy(s1, s2);
std::cout << "s1: " << s1 << '\n'; /// Should display "World"
std::cout << "The length of s1: " << myStrlen(s1) << "\n\n";
return 0;
}

Converting date format?

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
// declares variables
string dayow;
string month;
string day;
string year;
int main()
{
cout << "Pick you day of the week (ex: Monday-Sunday)" << endl;
getline(cin, dayow);
cout << " " << endl;
cout << "Pick your month (ex: January-December)" << endl;
getline(cin, month);
cout << " " << endl;
cout << "Pick your day of the month (ex: 1-31)" << endl;
getline(cin, day);
cout << " " << endl;
cout << "Pick your year" << endl;
getline(cin, year);
cout << " " << endl;
cout << "This is your date.." << endl;
cout << dayow << ", " << month << " " << day << ", " << year << "." << endl;
cout << " " << endl;
cout << "Here are the 3 formats to display your date.." << endl;
cout << " " << endl;
cout << "1. " << month << " " << day << " was a " << dayow << " in " << year << endl;
cout << " " << endl;
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string str = month;
std::string str2 = str.substr(0, 2);
std::string str = day;
std::string str3 = str.substr(0, 2);
std::string str = year;
std::string str4 = str.substr(0, 4);
std::cout << str1 << ", " << str2 << " " << str3 << " '" << str4 << endl;
return 0;
}
So what i'm trying to do here is get the user to input ex: Tuesday, March 22, 2012, then have 2 results come out. 1st being "January 1 was a Tuesday in 2012", that is fine as it is. Where the problem lies is the second result where I want "Tue, Mar 22, 2012" but the problem is on line 46 - 53, all of the strings are connecting to the first std:string str = dayow; so the output turns into TueTuTuTues!
Can anyone help?? thanks!
EDIT : Sorry if this is a noob questions :/ really new to coding!
Try this one: (some changes of your code)
#include <iomanip>
#include<iostream> // **add this header file**
#include <string>
#include <fstream>
using namespace std;
// declares variables
string dayow;
string month;
string day;
string year;
int main()
{
cout << "Pick you day of the week (ex: Monday-Sunday)" << endl;
getline(cin, dayow);
cout << " " << endl;
cout << "Pick your month (ex: January-December)" << endl;
getline(cin, month);
cout << " " << endl;
cout << "Pick your day of the month (ex: 1-31)" << endl;
getline(cin, day);
cout << " " << endl;
cout << "Pick your year" << endl;
getline(cin, year);
cout << " " << endl;
cout << "This is your date.." << endl;
cout << dayow << ", " << month << " " << day << ", " << year << "." << endl;
cout << " " << endl;
cout << "Here are the 3 formats to display your date.." << endl;
cout << " " << endl;
cout << "1. " << month << " " << day << " was a " << dayow << " in " << year << endl;
cout << " " << endl;
// **changes start here**
string str1 = dayow.substr(0, 3);
string str2 = month.substr(0, 3);
string str3 = day.substr(0, 2);
string str4 = year.substr(0, 4);
cout << str1 << ", " << str2 << " " << str3 << " ," << str4 << endl;
return 0;
}
Which compiler do you use? Your program shouldn't compile.
Add #include <iostream>
You cann't define few variables with same name C++.
So replace
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string str = month;
std::string str2 = str.substr(0, 2);
std::string str = day;
std::string str3 = str.substr(0, 2);
std::string str = year;
std::string str4 = str.substr(0, 4);
with
std::string str1 = dayow.substr(0, 3);
std::string str2 = month.substr(0, 2);
std::string str3 = day.substr(0, 2);
std::string str4 = year.substr(0, 4);
change this part:
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string str = month;
std::string str2 = str.substr(0, 2);
std::string str = day;
std::string str3 = str.substr(0, 2);
std::string str = year;
std::string str4 = str.substr(0, 4);
to:
std::string str = dayow;
std::string str1 = str.substr(0, 3);
std::string stra = month;
std::string str2 = stra.substr(0, 3);
std::string strb = day;
std::string str3 = strb.substr(0, 2);
std::string strc = year;
std::string str4 = strc.substr(0, 4);
problem was you had same variable name for day,month and year

stoi is not declared in this scope? [duplicate]

This question already has answers here:
Function stoi not declared
(13 answers)
Closed 8 years ago.
I am trying to convert a string into int using stoi() but i am getting error that error: ‘stoi’ was not declared in this scope. Here is the given code.
#include <iostream>
#include <string>
int main()
{
std::string str1 = "45";
std::string str2 = "3.14159";
std::string str3 = "31337 with words";
std::string str4 = "words and 2";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
// error: 'std::invalid_argument'
// int myint4 = std::stoi(str4);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
stoi is from C++11, you should try with atoi