0

So hello guys, its my code:

#include <iostream>
#include <string>

using namespace std;

void writeDown(string*t)
{
    for (int i = 0; *(t+i)!=NULL; i++)
    {
        cout << *(t+i) <<endl;
    }
}

int main()
{
    string t;
    getline(cin, t);
    string *wsk = &t;
    writeDown(wsk);
    return 0;
}

So I simply insert a string, and program should cout<< every single char from it in a new line. But here is what pops out:

binary '!=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)

What am I doing wrong?

Btw. I am working in VS 2013 for Win Desktop (btw. vol.2 - is it a good environment for C++ coding? - got 2015, but it's to slow on my laptop)

4
  • It looks like you're trying to treat std::string* like it's a char*. That's not how it works, they are very different things. Commented Jan 11, 2016 at 2:46
  • Awkay, maybe, so what's the correct way to do it? Commented Jan 11, 2016 at 2:47
  • If std::string is analogous to const char*, to what would std::string* be analogous? Commented Jan 11, 2016 at 2:51
  • @Frynio if my answer worked for you, will you be kind enough to mark it as accepted? Commented Feb 8, 2016 at 16:33

1 Answer 1

2

Well that code is bad in so many levels, but just to keep it simple and answer your question I would probably use iterators. Forget about that old C style if you are using C++.

Try this:

void writeDown(const string & t)
{
    for (string::const_iterator it = t.begin();
        it != t.end();
        ++it)
    {
        cout << *it << endl;
    }
}

Note that writeDown no longer takes a pointer as parameter but a constant reference to the string you want to print.

You will have to change your main to call writeDown:

string t;
getline(cin, t);
writeDown(t);

If you insist on using the "array" method you would have to use it like this, but ...

void writeDown(const string & t)
{
    for (int i = 0; t.c_str()[i] != NULL; i++)
    {
        cout << t.c_str()[i] << endl;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is it the same thing (by "the same" I mean speed) when I use asterix & or * as a parameter?
@Frynio Premature optimization is the root of stupid. Concentrate on writing code that's easy to understand and maintain then optimize based on the results of profiling.
Thank you. I would always do some sort of unimportant things, focusing on them, not on my main goal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.