unable to cout string in C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to programming and I can only use C++. I have been working on an RPG, and for some reason I can't get the program to print out the value that I set a string to. I started by defining the string "weapon" in void main.
void main()
{
string weapon;
cin >> weapon;
if(weapon = "A")
{
weapon == "sword";
}
}
I had the code sort of like this and I had a function above it that uses "weapon" (which was set to sword as you can see from the code above) at the end of something that I had it print out, but that was in the function (which was above the void main) so in order to get both to be defined variables I had to define them in both the void main and the function, but when I do that, nothing appears in the program when it's run. I had everything written correctly (what I put above is just an example) but the only way that it doesn't create an error is by defining it in both parts of the code. It says that one of them hasn't been defined yet so I defined it both the function and the void main. Why isn't it working? How do I fix it?
Thanks
P.S. I did include the string library and namespace.

void main() is illegal. It must be int main(), though some compilers will erroneously accept void main().
if(weapon = "A")
{
weapon == "sword";
}
It looks like you have this backwards. The single operator= sets weapon to the constant "A", regardless of what the user entered. The comparison operator== compares weapon with the constant "sword" and promptly discards that result. Perhaps you meant to use comparison in the if and assignment in the body of the if?

You're using = where you need ==, and vice versa. Should be:
if(weapon == "A") { weapon = "sword"; }

At least as I read it, you have code vaguely like this:
void f() {
string weapon;
cout << weapon;
}
int main(){
string weapon = "sword";
f();
}
...and the problem is that the value you're assigning to weapon in main isn't being used used when you call f.
Assuming that's roughly correct, what you're seeing is normal, expected behavior. The weapon you've defined in main is a separate variable from the weapon you define in f. Assigning a value to one has no effect on the other.
To get the desired effect, you need to "pass" the value from one to the other as a parameter:
void f(string w) {
cout << w;
}
int main() {
string weapon = "sword";
f(weapon);
}
This way, calling f gives it a copy of the current value that the weapon in main has been assigned, so f can use that same value.

You should look up for online tutorial, programming in C++. That is a good place to get started. Or buy a book on C++ programming.

Related

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.

This member function is not getting called, and I can't figure out how to rectify it [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 3 years ago.
Improve this question
I'm reading through my C++ textbook for an upcoming class, and following along an exercise in the book. This exercise compiles and seems to give the results that you would expect, but it seems there is an error though, and I can't figure out how to fix it.
Here is the code.
// Page 706 from text
//Contents of ThisExample.h
class Example
{
int x;
public:
Example(int a){x=a;}
void setValue(int);
void printAddressAndValue();
};
/*
//Contents of ThisExample.cpp
#include "ThisExample.h"
*/
#include <iostream>
using namespace std;
/*********************************************************
* Set value of object.
*********************************************************/
void Example::setValue(int a) // <---------- Doesn't execute
{ // <---------- Doesn't execute
x = a; // <---------- Doesn't execute
} // <---------- Doesn't execute
void Example::printAddressAndValue()
{
cout<< "The object at address " << this << " has "
<< "value "<< (*this).x<<endl;
}
/*
//Contents of main program
#include <iostream>
#include "ThisExample.h"
using namespace std;
*/
int main()
{
Example ob1(10), ob2(20);
// Print the addresses of the two objects
cout<<"Addresses of objects are "<< &ob1 << " and "<<&ob2<<endl;
// Print the addresses and values from within the member function
ob1.printAddressAndValue();
ob2.printAddressAndValue();
return 0;
}
In the book, they talk about replacing
void Example::setValue(int a)
{
x = a;
}
with
void Example::setValue(int a)
{
this->x = x;
}
But when I step through it with a debugger (which I am also new to), I don't see that function ever getting called.
I've tried commenting out the function entirely and it still runs, that's how I know it isn't getting called.
I also tried removing from the class
Example(int a){x=a;}
but then it doesn't compile. Any help? I just want to move along with the textbook, which is called "Starting Out With C++ Early Objects
Judy Walters, Godfrey Muganda, Tony Gaddis" and the exercise is on page 706.
Thanks
It doesn't ever get called, because you never call it.
The only place that the member variable x is set, in this particular example, is in the constructor. And the constructor happens to do so directly, rather than by calling setValue().
You could later call setValue() to change x, but currently you do not.
It's not uncommon to provide functionality that makes sense to be part of the class, even if you're not using that functionality quite yet. Although, unless you're writing a library, you generally wouldn't do too much of writing functionality you don't yet need.
Perhaps later exercises in the textbook involve calling setValue(). I would just continue reading and not worry about this.

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.

trouble making c++ student class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
For my assignment I have to make a program to read student data from standard input, sort it by last name / first name, and print out the result to standard output. Students consists of a last name, first name, and a grade point average. It says to there are no more than 50 students.
It also says you should not rely on an external library function to do the sort.
Here is the example:
Ware Henry 87.2
Dantes Edmond 91.4
Earhart Amelia 92.6
Here is how it should be sorted:
Dantes Edmond 91.4
Earhart Amelia 92.6
Ware Henry 87.2
Here is the code I have so far that is not working properly:
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
student();
void input();
void output();
void sort();
private:
string Fname;
string Lname;
float gpa;
}
student::student()
{
Fname = "";
Lname = "";
gpa = 0;
}
void student::input()
{
cout << "Enter first name, last name, and gpa"<<endl;
cin >> Fname >> Lname >> gpa;
}
void student::sort()
{
char temp;
int count = 0;
int i = 1;
while (i < word.size()) {
if (word[i - 1] > word[i]) {
temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
i++;
if (i >= word.size())
{
alpha(word);
}
}
else
{
count++;
}
}
return word;
}
void main()
{
student.input();
}
Any advice on where I went wrong and any possible solutions?
your student class has member variables to hold only one student, you need 50 instances of class student.
then you should hold these instances in an array/vector (whatever for container you are allowed to use) I assume you need to use a raw array so something like this will do.
student* students = new student[50];
what you then need is a compare function in your class to be able to sort the array, the compare function knows the internals of your class and you can decide how you want to sort the list e.g. after surname.
the sort function could be inside your class declared as a static function or maybe more logically an external function since student is not a container of student instances.
don't forget to delete the array when done
delete [] students;
in real world problems you would use std containers and e.g. algorithm sort for this kind of work.
Your compiler must have told you that word and alpha used in sort method are undeclared identifiers and count is assigned but never used.
Solution: Never ever steal code from wild wild web without understanding what it does. You may take others' code as inspiration, but blind copy-paste is a big no-no.
To give you a next step: you haven't even stored your students, you just input one, how would you sort just one entry? Think (and code) what you should use to store them and start working from there on how to sort them.
Good luck.
There are several reasons why your code is not working, first reason is that your class definition needs semicolon ';' at the end to close it.
class student
{
public:
student();
void input();
void output();
void sort();
private:
string Fname;
string Lname;
float gpa;
}; //semicolon here
In your sort() method the variable word is used but never declared, coding is not magic, the variable must declared and initialized before it is used like in your code.
while (i < word.size()) { //word must be declared somewhere
Also, in the sort method, you call a function alpha(word), this function does not exist in your program.
The sort method is of type void, which means it will not return anything, yet you are trying to return a string.
Another problem with the sort method is that it is never called from anywhere and will never be run.
There is also a big problem here with the way you are trying to use your class. To use the methods of the class you first have to instantiate an object of that class, you can then access the methods of the class through the object like this:
int main()
{
student theStudent;
theStudent;
theStudent.input();
return 0;
}
Another fundamental problem is that you are only going to get data for one object like this, you need to store several objects in something like an array and then sort the objects in the array:
int main()
{
student students[5];
for (int i = 0; i < 5; i++)
{
student newStudent;
students[i] = newStudent;
newStudent.input();
}
sort(students);
delete[] students;
return 0;
}
Which brings us to the sort method. It would be wise to not do the sorting as a method of the student class, but as a function called from main instead (like in the example above), that way it is easy to sort the array of student objects from main.
These are a few advice to start with, i am not going to do your complete homework for you though, if you use google and some of your precious energy, i believe that you will succeed.

Confused between the usage of constructors and what to/what not to place in them. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I had basics in C, and I've just started programming in c++ two weeks ago, and find 'classes' confusing. My question is how do i put a 'cin' to input the value to determine marks, and also how do i print the grades based on the below code? I'm only printing A to F and i'm so blur right now. And for some reason if i put 'else if' instead of just 'if' the error reads as missing ; before cout. Have way too many questions, sorry about that..
#include <iostream>
using namespace std;
class StudentMark {
private:
float mark;
public:
StudentMark() //constructor
{
mark = 0.0;
cout << "Constructed an instance of class StudentMark\n";
}
void SetMark(float markofstudent)
{
mark = markofstudent;
}
void IntroduceMark()
{
if (80<mark<100)
cout << "A" << endl;
if (65<mark<79)
cout << "B" << endl;
if (50<mark<64)
cout << "C" << endl;
if (40<mark<49)
cout << "D" << endl;
if (0<mark<39)
cout << "F" << endl;
}
};
int main()
{
StudentMark FirstStudent;
FirstStudent.SetMark(89);
FirstStudent.IntroduceMark();
}
Read about "Separation of concerns" - in this case, you're defining a class StudentMark which represents instances of a course grade. Therefore the class StudentMark should only be concerned with the score itself - it should not be concerned with program input and output - because (for example) what if you wanted to reuse your StudentMark class in a platform that didn't have a text-mode console, such as a web-application or console video game? So the responsibility of using cin and cout lies elsewhere.
Similarly the constructor of your StudentMark type should be concerned only with initializing a StudentMark instance. In your case you're simply zeroing-out the score member - you don't need an explicit constructor for this.
Finally, your IntroduceMark method looks like it's concerned with converting the numerical score to a grade-letter. That's all it should do - it should not be concerned with outputting it to the user of your program. I think getGrade is a better name that is more descriptive of its purpose.
class StudentMark {
private:
float mark = 0;
public:
void setMark(float mark);
char getGrade();
}
void StudentMark::setMark(float mark) {
this->mark = mark;
}
char StudentMark::getGrade() {
if( this->mark < 39 ) return 'F';
if( this->mark < 49 ) return 'E';
if( this->mark < 59 ) return 'D';
if( this->mark < 69 ) return 'C';
// etc
}
And then used like so:
int main(int argc, char* argv[]) {
StudentMark mark;
cout << "Instantiated a StudentMark" << endl;
mark.setMark( 70 );
cout << mark.getGrade() << endl;
}
Constructors are only used as a method of creating/initializing anything that's necessary for the class to function when an object of that class is created for the first time.
They're also used as means to provide default/user-input values to the class's variables.
They should be only run once when an object of the class is instantiated.
You should think of them as the "loading" process of your class.
Constructors are especially useful when working with databases for example, for the constructor is where the connection to the database happens, which is necessary if you wanted to manipulate the database using member functions.
What to put in constructors:
In general, anything that the class requires for it's member functions to function, including variables that weren't assigned values in previous code.
What not to put in constructors:
Practically anything else that isn't required for the class to function properly.
Here's an illustration of how constructors work.
class StudentMark {
public:
//Create variable m_mark, it hasn't been assigned a value,
// therefore contains junk for a value.
float m_mark;
//The constructor is called when an object of this class is created.
//Giving mark a default value of 0.0.
StudentMark(float mark = 0.0)
{
//m_mark contained junk, now it contains the value mark.
m_mark = mark;
}
}
int main()
{
//firstMark is instantiated, it's constructor gets called.
//Since we didn't provide any user input, the default value
//which is 0.0 gets assigned to firstMark.m_mark.
StudentMark firstMark;
//Now when secondMark is instantiated, it is provided with
//the value 80, therefore m_mark gets assigned the value 80.
StudentMark secondMark(80);
}
Finally, Learncpp has very informative tutorials on classes aswell as many other aspects of the language, I strongly recommend you give them a read.