Change a character from a 'char' in c++ - c++

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

Related

HackerRank: Day 1: Data Types in C++

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
}

How to combine few bacis chars into one string in c++

As a topic says. I try to combine few chars (from array) into one string.
i tried
char test[]={'A'};
char testt[]={'a'};
string testtt= test[0]+testt[0];
But it doesn't work.
char test[]={'A'};
char testt[]={'a'};
string testtt="";
testtt+=test[0];
testtt+=testt[0];
You can either use the constructor that takes char*, length.
#include<iostream>
#include<string>
int main(){
char test[]={'A'};
char testt[]={'a','w'};
std::string testtt= std::string(&test[0], 1) + std::string(&testt[1],1);/
std::cout<<testtt<<std::endl;
return 0;
}
or constructor that takes a range:
std::string testtt= std::string(&test[0], &test[1]) + std::string(&testt[0],&testt[1]);
It will do the trick ;)
#include <sstream>
string toStr(char* tab, int length)
{
stringstream ss;
for (int i=0 ; i<length; i++)
ss << tab[i];
return ss.str();
}
if you look inside class string you'll find that it doesn't overload copy constructor to take one character parameter.
you may think that you implement your own class containing a string object:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class MyStr
{
public:
MyStr(char c){ itsString = c;}
string GetStr()const {return itsString;}
private:
string itsString;
};
int main(int argc, char* argv[])
{
char test[]={'A'};
char testt[]={'a'};
MyStr testtt = test[0] + testt[0];
cout << testtt.GetStr() << endl;
cout << endl << endl << endl;
return 0;
}
this program runs and the compiler never complains BUT the result won't be as you may think: it won't be "Aa" but just: 'ت' because in fact the above statement: string testtt= test[0]+testt[0]; is equivalent to write: cout << (char)('A' + 'a');
which means summing two characters and the result is the integer ASCII value then this value will be converted back again to charater because you are really ivoking string(char); which will result to (charater of 162)

string subscript out of range c++

I need a help in a very basic c++ code.
My program is about guessing name game the problem which i faced is in reading string char by char
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void Play(int, int,int, string[], string[]);
string GetRandomName(int, int, int , string[], string[]);
const int ArrayMax = 100;
void Play(int selection, int FArraySize, int MArraySize,string Female[], string Male[])
{
int MAX_TRIES = 3;
int i=0;
ofstream ofFile;
ifstream InFile;
int num_of_wrong_guesses=0;
char letter;
string GuessedName;
GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);
cout << "Guess the following name:" << endl;
while (GuessedName[i]!= 0 ){
cout<<"?";
i++;
}
cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
cin >> letter;
return;
}
I don't complete coding...
the problem is in the while loop how can i solve it without using cstring?
could you help me?
int i = 0;
while(GuessedName[i] != 0)
{
cout << "?";
i++;
}
Seems like you are trying to print sequence of ? with the length of the string to guess. But you cannot treat std::string as c-string. When its length is n, GuessedName[n] is string subscript out of range - you cannot access one element past end - it's not null-terminated. Use for loop:
for(int i = 0; i < GuessedName.length(); ++i)
cout << "?";
Or simply:
cout << std::string(GuessedName.length(), '?');
Change the while loop like this:
while (GuessedName[i]){
cout<<"?";
i++;
}

Convert string to char for ascii

I want to ask for word from the user and then convert the word from string to char using 'strcpy'. Then I want to determine the sum of the ascii codes for all of the letters in the word.
However, I am having difficulties. I don't understand exactly how I can do that. This is what I have been able to do so far.
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
string word;
cout << "Enter word: ";
getline(cin, word);
/*
char w[word];
strcpy(w,word.c_str());
int ('A');
cout<<char(65);
*/
return 0;
}
The commented part is where I have been trying to do the converting. I copied the code from a worksheet. Even if it did work, I don't know how, and what it all means.
Thanks for your help.
char w[word];
strcpy(w, word.c_str());
char w[word] is incorrect. The square brackets is for the size, which must be a constant integral expression. word is of type std::string, so this makes neither logical nor practical sense. Maybe you meant it as:
char w = word;
But that still won't work because word is a string, not a character. The correct code in this case is:
char* w = new char[word.size() + 1];
That is, you allocate the memory for w using a char*. Then you use word.size() + 1 to initialize heap-allocated memory amounting to those bytes. Don't forget for the obligatory delete[] when you're finished using w:
delete[] w;
However, note that using raw pointers and explicit new is not needed in this case. Your code can easily be cleaned up into the following:
#include <numeric>
int main ()
{
std::string word;
std::getline(std::cin, word);
int sum = std::accumulate(word.begin(), word.end(), 0); /*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
std::cout << "The sum is: " << sum << std::endl;
}
You don't need to use strcpy() (or use a char * at all, for that matter), but this'll do your counting using a char pointer:
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
const char * cword = word.c_str();
int ascii_total = 0;
while ( *cword ) {
ascii_total += *cword++;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}
Output:
paul#local:~/src/cpp/scratch$ ./asccount
Enter word: ABC
Sum of ASCII values of characters is: 198
paul#local:~/src/cpp/scratch$
If you really do want to use strcpy(), I'll leave it as an exercise to you to modify the above code.
Here's a better way to do it, just using std::string (and C++11, and obviously presuming your system uses the ASCII character set in the first place):
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
int ascii_total = 0;
for ( auto s : word ) {
ascii_total += s;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}

Converting Input string to float/double C++

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.