So I know how to do it in C#, but not C++. I am trying to parse giver user input into a double (to do math with later), but I am new to C++ and am having trouble. Help?
C#
public static class parse
{
public static double StringToInt(string s)
{
double line = 0;
while (!double.TryParse(s, out line))
{
Console.WriteLine("Invalid input.");
Console.WriteLine("[The value you entered was not a number!]");
s = Console.ReadLine();
}
double x = Convert.ToDouble(s);
return x;
}
}
C++
?
?
?
?
Take a look at atof. Note that atof takes cstrings, not the string class.
#include <iostream>
#include <stdlib.h> // atof
using namespace std;
int main() {
string input;
cout << "enter number: ";
cin >> input;
double result;
result = atof(input.c_str());
cout << "You entered " << result << endl;
return 0;
}
http://www.cplusplus.com/reference/cstdlib/atof/
std::stringstream s(std::string("3.1415927"));
double d;
s >> d;
This is simplified version of my answer here which was for converting to an int using std::istringstream:
std::istringstream i("123.45");
double x ;
i >> x ;
You can also use strtod:
std::cout << std::strtod( "123.45", NULL ) << std::endl ;
Using atof:
#include<cstdlib>
#include<iostream>
using namespace std;
int main() {
string foo("123.2");
double num = 0;
num = atof(foo.c_str());
cout << num;
return 0;
}
Output:
123.2
string str;
...
float fl;
stringstream strs;
strs<<str;
strs>>fl;
this converts the string to float.
you can use any datatype in place of float so that string will be converted to that datatype. you can even write a generic function which converts string to specific datatype.
Related
Is there a way to change a single character in a char?
like this example
I have user input. The user should enter a number. If the number is float or double the user should enter a point. But if the User enters ',' (3,44 or 54,33)
my code doesn't work. Is there a general way to change the comma to point?
Like this:
char number1[50], number2[50];
number1 = 2,33;
number2 = 54,45;
turns into
number1 = 2.33;
number2= 54.34;
Thank you for any help!
Firstly you can not assign an int, double etc. to a char array.
So number[50] = 2,33; is meaningless.
You have to define the number as "array of char". What I mean? You should define the char array as char number[50] = "2,33";
#include <iostream>
int main()
{
char number[50] = "2,33";
number[1] = '.';
std::cout << number << std::endl;
return 0;
}
The output should be: 2.33
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main ()
{
char valor;
const char x = ',';
const char y = '.';
cout << "Please enter an char value: ";
cin >> valor;
/*Cast char to string*/
std::stringstream auxiliar;
std::string varfin;
auxiliar << valor;
auxiliar >> varfin;
/*Replace*/
std::replace(varfin.begin(), varfin.end(), x, y);
std::cout << varfin;
return 0;
}
Cast char to string for work methods of replace
Methods for replace
hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}
They are asking me to declare 3 variables, one for integer, one for double and one for string. Then read 3 lines of input from stdin. I have posted up my solution but it is not working. I don't know why my variable for string is not reading from the stdin. When I try it in the VSCODE, it is working. Can you tell me what am I doing wrong?
Here is the problem
Sample input:
12
4.0
is the best place to learn and practice coding!
Sample output:
16
8.0
HackerRank is the best place to learn and practice coding!
This is the code I use to check in my VSCODE. This works! But it doesn't work in HackerRank website.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.int x;
int x;
double y;
string str;
// Read and save an integer, double, and String to your variables.
cin >> x;
cin >> y;
getline(cin, str);
// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.
// Print the sum of both integer variables on a new line.
cout << x + i << endl;
// Print the sum of the double variables on a new line.
cout << y + d << endl;
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
cout << s + str << endl;
return 0;
}
After reading input using std::cin, there will be an extra line left which is read by the getline() everytime.
Try using std::cin.ignore() before reading the string.
It will ignore the extra line.
std::cin>>x;
std::cin.ignore();
std::getline(std::cin,str);
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.int x;
int x;
double y;
string str;
// Read and save an integer, double, and String to your variables.
std::cin >> x;
std::cin >> y;
std::cin.ignore();
getline(std::cin, str);
// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.
// Print the sum of both integer variables on a new line.
cout << x + i << endl;
// Print the sum of the double variables on a new line.
std::cout << std::fixed;
std::cout << std::setprecision(1);
cout << y + d << endl;
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
cout << s + str << endl;
return 0;
}
It work test here
I had the same problem before and i found that this problem because you can't use getline() and std::cin at the same time , so what's the solution for this problem ?
It's easy more than you think , just create 3 strings and read them using Getline() and then convert it from string to int using stoi(string) , and stod(string) to convert from string to double.
Here's the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
string ss, n, dd;
getline(cin, n); // string ---> must convert it to integer
getline(cin, dd); // string ---> must convert it to double
getline(cin, ss); // string
cout << int(stoi (n) + i) << endl;
cout << fixed << setprecision(1) << double(stod(dd) + d ) << endl;
cout << s << ss << endl;
return 0;
Hope that helps you with your problem.
use this
int num;
float db;
string str;
cin>>num;
cin>>db;
cin.get();
getline(cin,str);
cout<<i+num<<endl;
printf("%.1f\n", d + db);
cout<<s+str<<endl
Correct Answer
Github: https://github.com/Dushyantsingh-ds/30-Days-of-Code-hackerrank/blob/main/Content/Day%201:%20Data%20Types.md
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.
int i2;
double d2;
string s2;
// Read and save an integer, double, and String to your variables.
string tmp;
// Declare second integer, double, and String variables.
getline(cin, tmp);
i2 = stoi(tmp);
getline(cin, tmp);
d2 = stod(tmp);
getline(cin, s2);
// Print the sum of both integer variables on a new line.
printf("%i\n", i + i2);
// Print the sum of the double variables on a new line.
printf("%.1f\n", d + d2);
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
cout << s + s2 << endl;
return 0;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
int ii; double dd; string ss;
cin>>ii>>dd;
cin.ignore();
getline(cin,ss);
int isum=(i+ii);
double dsum=dd+d;
cout<<isum<<endl<<fixed<<setprecision(1)<<dsum<<endl<<s<<ss;
return 0;
//credits to Bytewise
}
I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
Unfortunately this did not work and I received this error message:
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
I've tried other methods that also did not work. This was the closest to working.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
I got most of my info here:
http://www.cplusplus.com/forum/beginner/75634/
(last two posts)
You need to put a double colon before toupper:
transform(input.begin(), input.end(), input.begin(), ::toupper);
Explanation:
There are two different toupper functions:
toupper in the global namespace (accessed with ::toupper), which comes from C.
toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Convert a String In C++ To Upper Case
Try this small program, straight from C++ reference
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
string s;
cin >> s;
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
cout << s;
return 0;
}
Live demo
You could do:
string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
name.at(i) = toupper(name.at(i));
}
Uppercase to Lowercase and viceversa using BitWise operators
1.
string s = "cAPsLock";
for(char &c: s)
c = c | ' '; // similar to: c = tolower(c);
cout << s << endl; // output: capslock
string s = "cAPsLock";
for(char &c: s)
c = c & ~' '; // similar to: c = toupper(c);
cout << s << endl; // output: CAPSLOCK
PS: for more info check this link
#include <iostream>
using namespace std;
//function for converting string to upper
string stringToUpper(string oString){
for(int i = 0; i < oString.length(); i++){
oString[i] = toupper(oString[i]);
}
return oString;
}
int main()
{
//use the function to convert string. No additional variables needed.
cout << stringToUpper("Hello world!") << endl;
return 0;
}
Like leemes said, you can use toupper(int). Like this:
void ToUpper(string &str) {
for (auto beg = str.begin(); beg != str.end(); ++beg) {
*beg = toupper(*beg);
}
}
It'll through in each character from str and convert it to upper. Example:
int main()
{
string name;
cout << "Insert a name: ";
cin >> name;
ToUpper(name);
cout << "Name in upper case: " << name << endl;
}
You can also use the function from code below to convert it to Upper-case.
#include<iostream>
#include<cstring>
using namespace std;
//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
int i;
char c[1 + 1];
memset(des, 0, sizeof(des)); //memset the variable before using it.
for (i = 0; i <= strlen(str); i++) {
memset(c, 0, sizeof(c));
if (str[i] >= 97 && str[i] <= 122) {
c[0] = str[i] - 32; // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
} else {
c[0] = str[i];
}
strncat(des, &c[0], 1);
}
}
int main()
{
char str[20]; //Source Variable
char des[20]; //Destination Variable
//memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
memset(str, 0, sizeof(str));
memset(des, 0, sizeof(des));
cout << "Enter the String (Enter First Name) : ";
cin >> str; //getting the value from the user and storing it into Source variable.
fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case
cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}
#include <iostream>
#include <sstream>
using namespace std;
int get_4()
{
char c = '4';
stringstream s(ios::in);
s << c;
int i;
s >> i;
return i;
}
int main()
{
cout << get_4() << endl;
}
The conversion is not working for me. If I write a character '4' or character array {'4','\0'} to stringstream and then read it out to int i, I don't get back the 4. What is wrong with the above code?
Because you set the stringstream to input-only -- no output.
If you check the fail() bit after trying to extract the int, you'll see it didn't work:
s >> i;
bool b = s.fail();
if( b )
cerr << "WHOA DOGGIE! WE BLOWED UP\n";
In your code, change:
stringstream s(ios::in);
to:
stringstream s;