Shobhit
Shobhit

Reputation: 123

Unable to print string by using cout << method(); where method() returns a string

following is my code

#include <iostream>
#include <string>
using namespace std;

string m(int x) {
    string h="";
    char q;
    for(int i=0;i<x;i++) {
        q=i;
        h +=q;
    }
    return h;
}

int main() {
int x;
cin >> x;
cout << m(x) << endl;

return 0;
}

but this is my output ,what are these strange looking square symbols. enter image description here

Shouldn't a string be printed because on every iteration a character is added.

Upvotes: 0

Views: 745

Answers (5)

Erik9631
Erik9631

Reputation: 117

First of all, what you are doing is essentially printing chars with values from 0 to x. If you look up the ascii table here: http://www.asciitable.com/ you can look at the numeric value of the character and see what it represents as a char. If it can not be represented, then console prints it out as squares you are seeing.

Now you are saying you want your code to be short and precise. Let me rework that a bit.

#include <iostream>
#include <string>
using namespace std;

string m(int x) {
    string returnVal;
    for (int i = 0; i < x; i++)
        returnVal += (char)i;
    return returnVal;
}

int main() {
    int input;
    cin >> input;
    cout << m(input) << endl;
    return 0;
}

Using letters as variable names is a terrible practice. Avoid that at all costs. Name your variables intuitively, so they are self describing. That is more important than having a "Short" and "precise" code.

Concerning that, you do not need the additional variable you named Q. You can directly typecast it into a char. Also avoid using {} if you can. It decreases code complexity and increases readability

Upvotes: 0

Mukarram Ishaq
Mukarram Ishaq

Reputation: 748

The second line of for loop should be like this

h +=to_string((int)q);

Upvotes: 0

Saboor
Saboor

Reputation: 352

You are mixing integers with strings. To concatenate string, first you have to convert a character,int to string. try the code below:

#include <iostream>
#include <string>
using namespace std;

string m(int x) {
    string h="";
    char q;
    for(int i=0;i<x;i++) {
        q=i;
        h += std::to_string(q);
    }
    return h;
}

int main() {
int x;
cin >> x;
cout << m(x) << endl;

return 0;
}

Upvotes: 4

alanwj
alanwj

Reputation: 539

Your terminal is likely trying to interpret the string as either ASCII or UTF8. Either way, most of the characters with a value up to 23 are going to be unprintable control characters.

If you started your loop at 33 instead of 0 you would get more sensible output.

Upvotes: 3

acraig5075
acraig5075

Reputation: 10756

Strings are strings, and ints are ints. Don't mix them up and expect magic.

Try this:

h += std::to_string(q);

Upvotes: 1

Related Questions