-2

It's not giving me any output and I don't know why.

I have tried switching for a while loop.

cin >> input;
for (z=0; z > input.size(); z++) {
input[z]=(int)input[z];
cout << input; }

Expected result:

Input = abc
output = 979899

No Error message.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
2 False
  • 1
  • 4
  • Assuming that `input` is a std::string, `string[z]` returns a `char`, that you convert to an int, that you store back into `input[z]`. In short, nothing happened. If you only need the output, do `for(auto const & c : input) {cout<<(int)c;}` – Gilles-Philippe Paillé May 19 '19 at 12:43
  • I try "cout << input;" but it doesn't output nothing. – 2 False May 19 '19 at 12:44
  • The thing is that I need this value to be stored in a string – 2 False May 19 '19 at 12:45
  • 1
    The reason it doesn't output anything is that the condition for exiting the loop is incorrect. It should be `<` instead of `>`. Also, an `std::string` contains `char`, which can be interpreted as characters or numbers. For example, the character `a` can be the letter `a` or the number 97 (without having to convert) depending on the usage. In other words, there is no need to convert it. – Gilles-Philippe Paillé May 19 '19 at 12:53
  • I think you'd better work on 2 strings. And the core of the treatment is to convert an `int` (well a `char`) to `string`, see https://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c – Sandburg May 19 '19 at 12:54
  • oh wow, I didn't noticed that. Thanks. – 2 False May 19 '19 at 12:56
  • You also need to decide if you want your code to work for an implementation (admittedly rare these days) that supports a character set that is not ASCII compatible. In that case `(int)input[z]` is not the ASCII value corresponding to `input[z]`. – Peter May 19 '19 at 13:04

1 Answers1

2

With the subscript operator [] you can only access one element from the string and you need to write more than one digit to the string ('A' -> "97"). To do that you need to convert the char value to a literal with std::to_string().

The simples solution is to use a second string as output, then you don't get in trouble with the indexing of the input string when you need to resize the string.

std::string str = "abc";
std::string out;
for(auto a : str )
{
     out.append(std::to_string((unsigned int)a));
}
std::cout << out << std::endl;
Kaonnull
  • 71
  • 4