convert string to number c++
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str = "123456";
int n;
stringstream ( str ) >> n;
cout << n; //Output:123456
return 0;
}
convert string to number c++
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str = "123456";
int n;
stringstream ( str ) >> n;
cout << n; //Output:123456
return 0;
}
string to number in c++
// For C++11 and later versions
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
// Output
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337
string to int c++
#include <iostream>
#include <string>
// namespace because why not
namespace dstd
{
int StringtoInt(std::string str)
{
int multiplier = 1;
int sum = 0;
for(int i = str.size() - 1;i >= 0; i--)
{
switch(str[i])
{
case '0':
sum += 0;
break;
case '1':
sum += 1 * multiplier;
break;
case '2':
sum += 2 * multiplier;
break;
case '3':
sum += 3 * multiplier;
break;
case '4':
sum += 4 * multiplier;
break;
case '5':
sum += 5 * multiplier;
break;
case '6':
sum += 6 * multiplier;
break;
case '7':
sum += 7 * multiplier;
break;
case '8':
sum += 8 * multiplier;
break;
case '9':
sum += 9 * multiplier;
break;
case '-':
sum *= -1;
break;
case ' ':
continue;
case
}
multiplier *= 10;
}
return sum;
}
}
int main()
{
//just an example of how to use the function
int a = dstd::StringtoInt("1992");
std::cout<<a<<'\n';
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us