user3002211
user3002211

Reputation: 183

String output gives weird letters

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    string s = "Too many tags";
    for(int i = 0; i < s.size(); i++){
        if(!(isspace(s[i]))){
            s[i] = '#' + s[i];
        }
    }
    cout << s << endl;
    return 0;
}

I'm trying to make a program which adds # tag before each letter in the string, but on output I get weird letters.. where is my mistake?

Upvotes: 1

Views: 121

Answers (3)

simonc
simonc

Reputation: 42165

s[i] = '#' + s[i];

modifies the value of an existing character. If you want to add new characters into your string, you should use insert:

s.insert(i, "#");

As Mark Ransom points out, you also need to move one further char through your string to avoid constantly adding "#" before the same letter. You could do this using

s.insert(i++, "#");

Note that you could always take VladimirM's advice and make slightly larger changes to something like

int i=0;
while (i<s.size()) {
    if (!isspace(s[i])) {
        s.insert(i++, "#");
    }
    i++;
}

Upvotes: 6

VladimirM
VladimirM

Reputation: 817

I add more: I think the simpler way is to use temporary variable otherwise your loop with 'insert' will go to endless loop and will hang:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    string s = "Too many tags";
    string res = "";
    for(int i = 0; i < s.size(); i++){
        if(!(isspace(s[i]))){
            res += "#";
        }
        res += s[i];
    }
    cout << res << endl;
    return 0;
}

Upvotes: 2

Yuushi
Yuushi

Reputation: 26040

This line:

s[i] = '#' + s[i];

isn't doing what you think it is. s[i] is a char, # is also a char. Adding these together doesn't give you the concatenation of the two characters, it gives you the addition of the integer code of the characters (so 35 for # and the ASCII code for whatever s[i] happens to be).

Upvotes: 4

Related Questions