tags:

views:

175

answers:

5

does this work on string in c++?

string s="lomi";
cout<<s<<endl;

what is bad in this code?

#include <iostream>
#include <cstring>
using namespace std;
int main(){

    string s=string("lomi");
    for (int i=0;i<s.length();i++){


         s[i]= s[i]+3;
    }


    std::cout<<s<<std::endl;









     return 0;
}

?

+4  A: 

short answer: yes

long answer: string s = "lomi"works due to the string(const char*) constructor.

Alexandre C.
it shows me mistake no operator << matches these operators
Try with std::cout << s << std::endl or with using namespace std.
Alexandre C.
string s = "lomi" invokes a constructor, not the assignment operator.
Alexandre C.
@Alexandre C: I would definitely not recommend the `using namespace` directive. It's dirty and prone to collisions. Better to promote either full qualification or `using std::cout;` syntax style.
Matthieu M.
@davit: What compiler did you use? Similar issues could be caused by using gcc instead of g++.
stefaanv
@Matthieu M. not on a 100k+ lines project full of STL...
Alexandre C.
i am using now visual c++ 2010
@Matthieu Sutter might disagree with that (I'm a fan so I'd disagree as well) for ADL-related reasons (imagine the std::swap example used to demonstrate ADL-associated problems and forgetting to specify a using declaration on that). It does invite collisions across libraries but I think the ADL case (which can cause runtime behavioral problems) is much more problematic than something which would generally result in a build error.
Technically for completeness, one should also specify using std::operator<< and so on with using declarations.
@stinky: Nope, std::operator<< will be called because of argument dependent lookup
Alexandre C.
@Alexandre C: Yes, there is no need to explicitly state `using` with functions (except `std::swap`). However I still maintain than the `using namespace` directive is a bad idea. Qualifying does not cost much, really, and the `using std::xxx` for the most commonly used items is sufficient.
Matthieu M.
+8  A: 

Yes.

(after you have #included the corresponding headers, and using the std namespace, etc.)


Edit: What's wrong with your code is you should

#include <string>

instead of

#include <cstring>

 

 

cstring is C's string.h header, which defines functions like strlen, strcpy, etc. that manipulates a C string, i.e. char*.

string defines C++'s string class which you're using.

KennyTM
thanks KennyTM very much
A: 

yes, cout in C++ knows how to deal with strings

Ravi Gupta
+2  A: 

Works for me -- does it work for you?

Remember to do this first:

#include <ostream>
#include <string>
using namespace std;
egrunin
A: 

Yes it should compile and work, if you want to print "lomi\n", and you have included <string> and <ostream> and declared using namespace std;.

Mau