-3

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!

3 Answers3

0

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

Buck Berry
  • 13
  • 3
  • ok I need this for user input and if the user enters, for example, the number 52,3 I need to change the ',' to '.'. – MaxHuber1234 Nov 10 '20 at 21:12
  • So you have to search for ',' in the char array. In modern C++ you can use just string for that. But if you want to manipulate whole array by yourself. You can use for loop and check each of the element of the array. When you find the position of the ',' you just stop and get the position. Then change the value of the number[position] as '.' – Buck Berry Nov 10 '20 at 21:23
0
#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;
}
BryanST25
  • 313
  • 2
  • 4
-2

Cast char to string for work methods of replace

enter image description here

Methods for replace

enter image description here

user4581301
  • 33,082
  • 7
  • 33
  • 54
BryanST25
  • 313
  • 2
  • 4
  • 1
    Text should be presented as text. There are [many, many good reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) why images should not be used in questions and answers unless the image being an image is important to the question or answer. – user4581301 Nov 10 '20 at 23:05
  • Hi. Excuse me. I did not know. – BryanST25 Nov 11 '20 at 00:55
  • Easily fixed, so you might as well do it. I'd love to get the downvote back. I hate leaving them around where kids could find them. – user4581301 Nov 11 '20 at 00:58