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 last year.
Improve this question
Hi this is my first subject (question) at stack overflow i've tried an project about c++ classes at Code::Blocks but something went wrong
#include <iostream>
using namespace std;
class char1
{
public:
string charName;
float charLength;
void printName()
{
cout<<"char name is"<<charName;
}
};
int main()
{
int charNAME;
float charLENGTH;
cout<<"write your char's name"<<endl;
cin>>charNAME;
cout<<"write your char's length"<<endl;
cin>>charLENGTH;
char1 name;
char1 length;
name.charName=charNAME;
length.charLength=charLENGTH;
return 0;
}
when i run program it asks me char's name i write something, after it asks char's length
but program end there i cant do anything
here is picture for help
Some fixes for your code to show you how to use your class in practice (with some
c++ coding tips).
#include <string>
#include <iostream>
// using namespace std; <== don't do this
// https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
//class char1
class Character // <== give classes clear names, makes code more readable
{
public:
std::string name;
float length;
// I understand you want to do this to test stuff.
// but from a design point of view printing is not something
// a character can do to himself
/*
void printName()
{
cout << "char name is" << charName;
}
*/
};
// bit offtopic but :
// if you want to add support for printing your character
// its more common to overload operator<< for streams like this
std::ostream& operator<<(std::ostream& os, const Character& character)
{
os << "Your character's name = " << character.name << ", and his/her length = " << character.length << "\n";
return os;
}
int main()
{
// int charNAME; in your class this is a string, be consistent.
// float charLENGTH;
// make an instance of the Character class
Character character;
std::cout << "Enter your char's name : "; // << endl; avoid using endl use "\n" if you want a newline
std::cin >> character.name;
std::cout << "Enter your char's length : "; // << endl;
std::cin >> character.length;
std::cout << "\n";
std::cout << character; // this will now call your overloaded << operator
return 0;
}
Related
Hi i am trying to write a c++ program where the user will enter a name lets say for example: Tahmid Alam Khan Rifat and the computer will print the formatted version of the name which in this case will be: Mr. T. A. K. Rifat. I have included the code below. You will be able to see that I got close but still not exactly what i wanted. Please help.
#include<iostream>
#include<string>
using namespace std;
class myclass{
private:
string name,temp;
string p;
int i,j,sp;
public:
void work(){
cout << "Enter the name of the male student: ";
getline(cin,name);
cout << endl;
cout << "The original name is: ";
cout << name;
cout << endl << endl;
cout << "The formatted name is: " << "Mr." << name[0] << ".";
for(i=0;i<name.size();i++){
if(name[i]==' '){
sp=i;
for(j=sp+1;j<=sp+1;j++){
temp=name[j];
cout << temp << ".";
}
}
}
for(i=sp+2;i<name.size();i++){
cout << name[i];
}
cout << endl;
}
};
int main(){
myclass c;
c.work();
}
I guess the easiest way to solve this is to tokenize your string, print the first character from it, except from the last, where you print its full size.
To tokenize, you can do something like that:
std::vector<std::string> tokenize(std::istringstream &str)
{
std::vector<std::string> tokens;
while ( !str.eof() ) {
std::string tmp;
str >> tmp;
tokens.push_back(tmp);
}
return tokens;
}
Now you can easily transverse the tokens:
int main()
{
std::string name;
cout << "Enter the name of the male student: ";
getline(cin,name);
cout << endl;
cout << "The original name is: ";
cout << name;
cout << endl << endl;
std::istringstream str(name);
std::vector<std::string> tokens = tokenize(str);
for ( int i = 0 ; i < tokens.size() - 1; ++i)
std::cout << tokens[i][0] << ". ";
cout << tokens[tokens.size() - 1] << endl;
}
I hope this helps :)
It is probably a simpler version (originally I wrote this in C, you could easily convert it to C++ though, since the logic remains the same).
I have accepted the name and then inserted a space at the beginning of the string and one more space at the end, before the NULL character ('\0')
The program checks for a space.
When it encounters one, it checks for the next space that occurs in the string.
Now occurrence of this space helps us to identify an important determining factor as to what the next action should be.
See, if there is an null character after this subsequent space, then we can conclude that the subsequent space was the one we inserted at the end of the string.
That is, the space which occurs after the primary space, which came before the surname. Bingo!
You get the precise index of the array, from where the surname starts! :D
Looks long, but really is simple. Good luck!
#include<stdio.h>
#include<string.h>
void main()
{
char str[100]; /*you could also allocate dynamically as per your convenience*/
int i,j,k;
printf("Enter the full name: ");
gets(str);
int l=strlen(str);
for(i=l;i>=0;i--)
{
str[i+1]=str[i]; //shifting elements to make room for the space
}
str[0]=' '; //inserting space in the beginning
str[l+1]=' '; str[l+2]='\0'; //inserting space at the end
printf("The abbreviated form is:\n");
for(i=0;i<l+1;i++) //main loop for checking
{
if(str[i]==' ') //first space checker
{
for(j=i+1; str[j]!=' ';j++) //running loop till subsequent space
{
}
if(str[j+1]!='\0') //not the space after surname
{
printf("%c.",str[i+1]); //prints just the initial
}
else
for(k=i+1;str[k]!='\0';k++) //space after surname
{
printf("%c", str[k]); //prints the entire surname
}
}
}
}
Change your loop to the following:-
for(i=0;i<name.size();i++)
{
if(name[i]==' ')
{
initial = i + 1; //initial is of type int.
temp = name[initial]; //temp is char.
cout << temp << ".";
}
}
Try ravi's answer to make your code work, but I wanted to point out that there are more intuitive ways to program this which would make maintenance and collaboration easier in the future (always a good practice).
You can use an explode() implementation (or C's strtok()) to split the name string into pieces. Then just use the first character of each piece, disregarding the last name.
I think your question has already been answered. But in the future you could consider splitting up your program into more simple tasks, which makes things easier to read. Coupled with descriptive variable and function names, it can make a program easier to comprehend, and therefore to modify or fix later on.
Disclaimer - I am a beginner amateur programmer and this is just for ideas:
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
// I got this function from StackOverflow somewhere, splits a string into
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
std::istringstream is(line);
return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names {
private:
std::vector<std::string> full_name_;
void TakeInput() {
std::cout << "Enter the name of the male student: " << std::endl;
std::string input;
getline(std::cin,input);
full_name_ = LineSplit<std::string>(input);
}
void DisplayInitialsOfFirstNames() const {
std::cout << "Mr. ";
for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
std::cout << full_name_[i][0] << ". ";
}
};
void DisplayLastName() const {
std::cout << full_name_.back() << std::endl;
}
public:
void work() {
TakeInput();
DisplayInitialsOfFirstNames();
DisplayLastName();
};
};
int main(){
Names n;
n.work();
}
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 8 years ago.
Improve this question
I've been debugging this for a long time now - but I have no clue what the issue is.
I get a name from the console (via std::cin) and then proceed to create a new Player object with it. Then I pass the new object to the Gameboard to be added to a std::vector<J> where J is part of a template. Here's the code:
main.cpp
Gameboard<Tile,Player,5,5> board = Gameboard<Tile,Player,5,5>();
std::string name;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
std::cout << std::endl;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
std::cout << std::endl;
std::cout << "Enter a name: "
std::cin >> name;
board.setPlayer(Player(name));
gameboard.h
template<class T, class J, const int X, const int Y>
class Gameboard {
std::vector<J> players;
public:
void setPlayer(J player);
};
template<class T, class J, const int X, const int Y>
void Gameboard<T,J,X,Y>::setPlayer(J p) {
////// DEBUG CODE //////
std::cout << p.getName() << std::endl;
players.push_back(p);
for (int i = 0; i < players.size(); i++) {
std::cout << players.at(i).getName() << std::endl;
}
}
player.h/player.cpp
class Player {
std::string name;
public:
Player(std::string _name);
std::string getName();
};
Player::Player(std::string _name) {
name = _name;
}
std::string Player::getName() {
return name;
}
I think I've tracked my problem down to the code marked DEBUG CODE. Using the above code, and entering the names Bob, Joe, and Tim, I would get the following output:
Enter a name: bob
bob
Enter a name: joe
joe
Enter a name: tim
tim
[exit]
So somehow, when I add the player to the vector, it becomes corrupted or something similar. The object is valid right before insertion because I echo out the name. The vector is also growing in size because it's printing blank lines equal to the number of players added.
What is going on?
You might have a copy constructor where you are not copying the name. So when you push_back on the vector, a Player object with empty name gets pushed on the vector.
Implement the copy constructor properly and it should work
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 8 years ago.
Improve this question
I made a program that should take input print it. Then run a simple addition thing but when i use spaces in the input it skips through the addition. I do not know what the problem is.
this is the class stuff
#include <iostream>
#include <string>
using namespace std;
class Cheese {
private:
string name;
public:
void setName(string x){
cin >> x;
x = name;
}
string getName(){
return name;
}
void print(){
cout << name << endl;
}
};
this is the main stuff
int main()
{
string h;
Cheese hole;
hole.setName(h);
hole.getName();
hole.print();
this part is getting skipped through without letting me input
int x = 5;
int y = 16;
cout << x+y;
num(x);
int a;
int b;
int c;
cout << "Type in a number and press enter.";
cin >> a;
cout << "Repeat.";
cin >> b;
c = a+b;
cout << c << endl;
if(c <= 21){
cout << "Good job!";
}
else {
cout << "You fail!";
}
return 0;
}
I suggest you divide the responsibilities a little differently. The Cheese class's setName function should simply take a string and set the instance's member variable to the given argument.
Then your program can read from standard input and populate a string within main, and pass that string to setName.
To be more concrete:
class Cheese {
private:
string name;
public:
void setName(const string& x){
// change this code to set the 'name' member variable
}
[...]
};
And the main becomes:
int main()
{
string h;
Cheese hole;
std::string input_name;
cout << "Type a name and press enter.";
cin >> input_name; // Will read up to first whitespace character.
hole.setName(input_name);
hole.getName(); // this is a no-op: compiler may warn of unused return value
hole.print();
In general, reading standard input as part of a class's interface is a bad idea, because it makes it hard to re-use that class in the future (for example, with programs that take input from a file instead of from a human at a console).
The input that you pass to cin input stream skips any white space, Tab space or newline. If you wish to input string then you can use cin.getline(string s). The input after the white space gets passed to next waiting cin, as the next cin accepts integer and it get a character string it skips that. Thus when enter a string with white spaces the program skips the remaining part.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am trying to link my student_info structure with my read_name function but I am having issues getting it to work properly and it won't compile. The errors I am getting now are error: ‘first_name’ was not declared in this scope and error: ‘last_name’ was not declared in this scope. I declared them in the structure however.
Here's my code:
#include <iostream>
using namespace std;
//Place your structure here for Step #1:
struct student_info
{
char first_name[15];
char last_name[15];
char crn[15];
char course_designator[15];
int section;
};
//Place any prototypes that use the structure here:
void read_name(student_info & first_name[], student_info & last_name[])
{
cout << "enter first name" << endl;
cin.getline(first_name, 15, '\n');
cout << "enter last name" << endl;
cin.getline(last_name, 15, '\n');
first[0] = toupper(first_name[0]);
last[0] = toupper(last_name[0]);
cout << "your name is " << first_name << " " << last_name << endl;
}
int main()
{
//For Step #2, create a variable of the struct here:
student_info student;
read_name(first_name, last_name);
return 0;
}
Things you can do to fix your problem.
Change read_name to take a reference to a student_info.
void read_name(student_info & student)
Change the implementation of read_name to read the data into the first_name and last_name members of info.
void read_name(student_info & student)
{
cout << "enter first name" << endl;
cin.getline(student.first_name, 15, '\n');
cout << "enter last name" << endl;
cin.getline(student.last_name, 15, '\n');
first[0] = toupper(student.first_name[0]);
last[0] = toupper(student.last_name[0]);
cout << "your name is " << student.first_name << " "
<< student.last_name << endl;
}
From main, call read_name using student as argument.
int main()
{
//For Step #2, create a variable of the struct here:
student_info student;
read_name(student);
return 0;
}
I'm writing a program that allows me to put my name in and pull up different semesters and for me to put grades in and then be able to calculate my class average and GPA, just for my own reference in my courses.
What I am having a problem with is with structures and how they work with a multifunction program. In my courses we have not covered this and I have spent a while now searching for answers and cannot find one. Below is my current code:
using namespace std;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char gettingName();
class Student{
public:
double semesterClass[20][20]; //first is for semester, second is for which class
char name[20];
int semester;
int numOfCourses;
};
int main(int argc, char **argv)
{
Student info;
gettingName();
cout << "Hi my name is: " << name.info << endl;
return 0;
}
char gettingName()
{
Student info;
char YesNo[5];
char boolean[1] = {'T'};
char yes[3] = {'Y','e','s'};
char yes2[3] = {'Y','E','S'};
char yes3[3] = {'y','e','s'};
char yes4[1] = {'Y'};
char yes5[1] = {'y'};
while(boolean[0] == 'T'){
cout << "What is your name? ";
cin >> info.name;
cout << endl;
cout << "Is your name " << info.name << "?"<<endl; //accepted input will be Y,y,YES,Yes,yes
cin >> YesNo;
//if input does not equal any of the accepted inputs, then loop until it does
if((strcmp(YesNo,yes) == 0) || (strcmp(YesNo,yes2) == 0) || (strcmp(YesNo,yes3) == 0) || (YesNo[0] == yes4[0]) || (YesNo[0] == yes5[0])){
boolean[0] = 'F';
}
}
return 0;
}
My question: how might I go about fixing the scope so that I can call the 'gettingName' function, get the person to input their name, (get it right (that already works)) and then be able to access and print it in the main function?
There are a lot of issues with your code, but I will try to help out the best I can. In general C++ scope for local variables is at the block level. So any time you see a ending bracket }, the scope has ended.
Some specific issues with your code that I noticed:
This line should be: "cout << "Hi my name is: " << info.name <<
endl;", not name.info
The boolean loop can be handled much more efficiently. You should try to list all of the acceptable options in one data structure like an array and then loop through the array.
Lastly when creating a function that doesn't need to return anything,
you can use the type void instead of char. So it could be void gettingName(), instead of char gettingName().
As an example to show you a quick and easy way to do what I think you wanted, I simplified your code a bit. I also decided to use std::string rather than char arrays as they are easier to work with:
class Student{
public:
std::string name;
};
std::string gettingName();
int main()
{
Student Info;
Info.name = gettingName();
cout << "Hi my name is: " << Info.name << endl;
return 0;
}
std::string gettingName()
{
std::string name;
cout << "What is your name? ";
cin >> name;
cout << endl;
return name;
}
Your code not really is object oriented. To fix the scope, you'll have to put gettingName inside your class to make it a member function (which is btw the term to Google for). You will also have to change the implementation which then needs to include the class name for identification:
char Student::gettingName()
{
...
}
From main you'd call it then via
info.gettingName();