0

I am a beginner and I am practicing C++ on UVa.

Problem link: P458

My IDE is showing an error in line 15 decoded = decoded + (s[i] - 7);

My code:

#include <iostream> #include <string> using namespace std; int main() { string s; while (cin >> s) { string decoded; int len = s.length(); for (int i = 0; i < len; i++) { decoded = decoded + (s[i] - 7); //15 no line } cout << decoded << endl; } return 0; } 

But when I write the line like this decoded += (s[i] - 7); it shows no error.

Please explain why this is happening?

Thanks in advance.

4
  • 2
    It's recommended to include the error message into the question itself. Commented Dec 29, 2020 at 14:22
  • 1
    Also, what exactly do you want the code to do when you write that? Commented Dec 29, 2020 at 14:23
  • Ok sir, I will mind it. Commented Dec 29, 2020 at 14:39
  • edit this question to do that. Commented Dec 29, 2020 at 14:40

2 Answers 2

2

Please explain why this is happening?

std::string has a method overload std::string::operator+= that accepts type char. That what makes this line:

decoded += (s[i] - 7); 

to compile. But when you write:

decoded = decoded + (s[i] - 7); 

that requires (s[i] - 7) to be implicitly converted to std::string or something that std::operator+ overload to accept. Simplest solution is to create a temporary string:

decoded = decoded + std::string( 1, s[i] - 7); 

or just use operator+= which works as intended. Or even simpler is to modify s in place:

string s; while (cin >> s) { for( char &c : s ) c-=7; cout << s << endl; } 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to convert (s[i] - 7) which is an int to std::string

#include <iostream> #include <string> using namespace std; int main() { string s; while (cin >> s) { string decoded; int len = s.length(); for (int i = 0; i < len; i++) { decoded = decoded + std::to_string((s[i] - 7)); //15 no line } cout << decoded << endl; } return 0; } 

4 Comments

Which is usually but not always what the op wants.
A simple char cast should be enough for C++11 and up
@Harry sir, but it is showing int output when I use it decoded = decoded + std::to_string((s[i] - 7));
then I think you need to look at what @scohe001 commented. Can you share the input and expected output information