c++ Making one std::string to another [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
As you probably would be able to tell from my question,, I'm a c++ newbie
I'm not sure what's the right way to copy one string's value to another..
For instance I did this:
std::string x = "this is x";
std::string y = "this is y";
x = y;
No error,, but this does not do anything..
I know there is string::copy... but seems like this function needs buffer size, etc.. which is annoying..
Is there a simple way to do this job in c++?
Thanks
UPDATE!!
Sorry,, I think I simplified my answer too much.....
This is my situation:
class MyClass {
std::string m_str = "OLD STRING";
}
void CopyString(MyClass& c, std::string x) {
c.m_str = x;
}
int main() {
MyClass c;
CopyString(c, "NEW STRING");
std::cout << c.m_str << std::endl; // prints "OLD STRING"!!
}

Your code
std::string x = "this is x";
std::string y = "this is y";
x = y;
is correct, and copies the value of the y variable, to the x variable.
Your assertion
” this does not do anything.
is – happily – incorrect.

when you do x = y, it will copy the value of y into x, thus, make x will be this is y

All though its not the best implementation (get/set methods would be better), you need to make m_str public. When using a class, if you don't set it differently all variables are set to private by default. Change it to this and it should compile and run.
class MyClass {
public:
std::string m_str = "OLD STRING";
};
EDIT: you also forgot your semicolons at the end of your class and copy methods.

Related

ofstream object as variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 15 days ago.
Improve this question
I am trying to create multiple files according to a filename in cpp. Using ofstream for that, I could not achieve it for now.
I'd appreciate if anyone can help me with that.
I am writing down here:
static std::ofstream text1;
static std::ofstream text2;
class trial{
public:
if(situation == true) {
document_type = text1;
}
if(situation == false) {
document_type = text2;
}
document_type << "hello world" << "\n";
}
ofstream object as variable.
Assignment copies the objects, and it's not possible to create copies of streams. You can only have reference to streams, and you can't reassign references.
Instead I suggest you pass a reference to the wanted stream to the trial constructor instead, and store the reference in the object:
struct trial
{
trial(std::ostream& output)
: output_{ output }
{
}
void function()
{
output_ << "Hello!\n";
}
std::ostream& output_;
};
int main()
{
bool condition = ...; // TODO: Actual condition
trial trial_object(condition ? text1 : text2);
trial_object.function();
}
Also note that I use plain std::ostream in the class, which allows you to use any output stream, not only files.
You can't use statements at class scope, only declarations.
In any case, you need to use a reference variable for what you are attempting, eg:
std::ofstream& document_type = situation ? text1 : text2;
document_type << "hello world" << "\n";

String in a class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was working on a project and I've had a question: when I call a class that contain a string str, does the code create a string every time or it use the string I've already created?
For example:
#include <iostream>
using namespace std;
class exClass {
public:
void exVoid ( string valueStr )
{
str = "Hi";
cout << str;
}
private:
string str;
};
int main()
{
exClass myClass;
string stringMain;
while (1)
{
cout << "Insert value of str: ";
cin >> stringMain;
myClass.exVoid(stringMain);
}
}
so the question is: every time I call exClass, the class create the string str or it do that only once (when I call it for the first time)?
Following the flow of the program:
First you create an instance of exClass named myClass. This happens once.
Then you create a string named stringMain. This also happens once.
After that, you have an endless loop while(1). Inside this loop you:
Print on the output
Get input
Call function exVoid()
So, you create one instance of class exClass with one member str and use the same str (through your function) endlessly inside your loop.
Something to think about is the function argument. You never really use it. For it to have meaning in you code, you can do something like:
void exVoid ( string valueStr )
{
str = valueStr;
cout << str;
}
Yes, you're creating a copy of your input string every time you call exVoid. You can make it more efficient if you use a reference:
void exVoid(const std::string &value) {
...
}
The way you're calling it from main, you're thus passing a reference to stringMain, but by making it const, you know your method won't mess with it.

C++ direct and copying initialization problem with constructor [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have started doing C++ clases for over 2 weeks now and I have a small problem that i dont know how to solve. I have to make a simple Class with one int parameter. That class needs to work with direct and copying initilaization and needs to print message which initialization is used. For example:
TestClass T(60) //this should print a message "Direct initialization"
TestClass T = 205 // this should print a messagte "Copying initialization"
If you use a constructor with a single variable initialization, then this assignment operation will be done for you automatically. See my code below:
#include<bits/stdc++.h>
using namespace std;
class A {
int x;
public:
A(int xx) {
cout << "Constructor Called" << endl;
x = xx;
}
print() {
cout << "Value of obj is " << x << endl;
}
};
int main() {
A v = 10;
v.print();
}
Because you used initialization constructor, = operator was handled automatically. To prove that it is using the constructor, I used cout in constructor and created and called another printing function.

While going through the mcqs of Techgig event in india i had problem on the following code. Help me understand the following code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
#include<iostream>
using namespace std;
class abc
{
static int x;
public:
abc()
{
x++;
}
static int getx()
{
return x;
}
};
int abc::x=0;
int main()
{
cout<<abc::getx()<<" ";
abc t[10];
cout<<abc::getx();
}
While going through the mcqs of Techgig event in india i had problem on the following code. Help me understand the following code.
what does the line abc t[10] means?
what does the line abc t[10] means?
It means that you get 10 abc on the stack and that you will refer to them by t. Just like int t[10] gets you 10 int, except instead of int, it's abc.
But you probably wondered what this example is supposed to demonstrate with it. We have a static variable in class abc, so this one exists only once, no matter how many abc are made:
static int x;
It is set to 0 here:
int abc::x=0;
At the start of the program we confirm that it indeed is 0:
cout<<abc::getx()<<" ";
This should print 0, because it's calling a static getter that returns that x value:
static int getx()
{
return x;
}
Now, what's happening here?
abc t[10];
Here, 10 abc are made. Actually, in reality not much might be made here because abc doesn't have any non-static fields. But nevertheless, the constructor is called every time:
abc()
{
x++;
}
Remember, 10 abc are made, so this is called 10 times. Thus, x is increased by 1 ten times, and since it was 0, it should now be 10. We confirm this assumption with the following print:
cout<<abc::getx();

Can't set the string type second time, inside the class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have class
class Item
{
private:
string name;
public:
void set_data()
{
getline(cin, name);
}
}
From the main function I am setting the value of the name once, but when I want to give it another value, I can't. I mean that the second time when I call the function from the same object, it does nothing.
First of all, in C++ your implementation should be separate from the declaration unless you are using templates which you are not. This is not Java.
Second, your sample code is missing a closing brace. I have submitted an edit to add it and improve your code formatting.
That aside, the following implementation works for me:
Item.h
class Item
{
private:
std::string name;
public:
void set_data();
void printName();
};
Item.cpp
void Item::set_data()
{
std::cout << "Type name and hit return: " << std::endl;
getline(std::cin, name);
}
void Item::printName()
{
std::cout << "Name is : " << name << std::endl;
}
main.cpp
// Entry point
int main(int argc, char** argv)
{
// Yes I thought I would mix things up and use new instead of Item i; So shoot me.
Item * i = new Item();
i->set_data();
i->printName();
i->set_data();
i->printName();
delete i;
return 0;
}
The application will wait at both calls to set_data() for me to type something in and hit return. Then it continues as normal. I added a text prompt so it is less confusing to see in the console. I get this:
Does this in some way answer your question? If you are doing something else in main() then try stripping it out back to just this simple action then add the other stuff back in until you find the bit that introduces the problem.
UPDATE:
As prompted by the comments below, if you put std::cin >> before another call to getline() it will read the first word from the stream and leave the rest of your string and the \n character in there which getline() uses for its delimiter. So next time you call getline() it will automatically extract the rest of the string from the stream without requesting user input. I guess this is probably what you are seeing.