I'm trying to study c++ about array
and I'm having a problem displaying the name from the array name
Because when I try to display the name of the passenger based on where he seat
the first letter becomes the last letter of his name..ahmm
Here's my code
#include <iostream.h>
#include <conio.h>
char* name[10]={" "};
int* seat=0;
char* pname="The Passenger is: ";
char ask;
void display();
int main()
{
clrscr();
cout<<"The Entering of name and seat number..."<<endl;
do
{
cout<<"\nEnter your name: ";
cin>>*name;
cout<<"Enter your seat number: ";
cin>>*seat;
cout<<"Do you want to input again?(Y/N): ";
cin>>ask;
}
while(ask=='y'||ask=='Y');
cout<<"\nDo you want to see the passenger's name?(Y/N): ";
cin>>ask;
if(ask=='y'||ask=='Y')
{
cout<<"\nThe Program will now direct you to the displaying of passenger's name...."<<endl;
display();
}
else
{
cout<<"\n\nThe Program will end shortly....";
}
getch();
return 0;
}
void display()
{
do
{
cout<<"\nEnter seat number to display passenger's name: ";
cin>>*seat;
cout<<pname<<*name[*seat-1]<<endl;
cout<<"Do you want to try again?(Y/N): ";
cin>>ask;
}
while(ask=='y'||ask=='Y');
cout<<"\nThe Program will now end shortly....";
getch();
}
To display the name from the array name you have at first to define the array correctly.:)
If you do not know yet about standard class std::string then the array should be defined as for example
char name[10][20];
that is it can store 10 names that have length no more than 20 characters.
Or if you know about class std:string then you can define it as
#include <string>
std::string name[10];
And it would be even better to define
#include <string>
#include <array>
std::array<std::string, 10> name;
For this program neither pointer is needed to be defined.
Take into account that when you ask to enter a seat number you should check that this number is in the range 1 - 10 (in this case you will need to decrease it by one when will use it to access the array) or 0 - 9.
You seem to be having a problem with pointers. Namely
int* seat=0;
will not allocate space for the integer, but instead allocate space for a pointer and then set this pointer and set it to address 0. When you perform
cin>>*seat;
Your program attempts to dereference the pointer which does not point to anything. Furthermore when you perform
cin >>*name
You are not writing to the whole string but instead writing to the dereference location, namely the first character of the string.
For a start change
int* seat=0;
to
int seat = 0
and
cin>>*name;
to
cin>>name;
good luck!
Edit:
also you want to change the:
cin >> *seat;
to
cin >> seat
Nevertheless you might need some more practice in the basic language features, like pointers, you could use some existing data structures. Since you are using cout and cin i assume your compiler supports the C++ standard library. I would use a map, to save the passengers.
#include <iostream>
#include <map>
struct passenger
{
char name[10];
};
std::map<int, passenger> passengers;
int seat;
char ask;
void display();
int main()
{
std::cout<< "The Entering of name and seat number..." << std::endl;
do
{
passenger p;
std::cout << "\nEnter your name: ";
std::cin >> p.name;
std::cout << "Enter your seat number: ";
std::cin >> seat;
// add passenger to the map
passengers.insert(std::pair<int, passenger>(seat, p));
std::cout << "Do you want to input again?(Y/N): ";
std::cin >> ask;
}
while(ask=='y'||ask=='Y');
std::cout << "\nDo you want to see the passenger's name?(Y/N): ";
std::cin >> ask;
if(ask=='y' || ask=='Y')
{
std::cout << "\nThe Program will now direct you to the displaying of passenger's name...." << std::endl;
display();
}
return 0;
}
void display()
{
do
{
std::cout << "\nEnter seat number to display passenger's name: ";
std::cin >> seat;
// check if passenger data is available for this seat
if(passengers.find(seat) != passengers.end()) {
std::cout << "The Passenger is: " << passengers[seat].name << std::endl;
} else {
std::cout << "Seat still available ..." << std::endl;
}
std::cout << "Do you want to try again?(Y/N): ";
std::cin >> ask;
}
while(ask=='y' || ask=='Y');
}
If you are using a pointer *seat you don't have to access it as
cin>>*seat. You only need to write cin>>seat.
While you are learning cpp, check out what pointers are too.
Here's a little info on that too, though that is not exactly the subject matter,
int *S; // pointer of type int
int x; // variable of type int
S = &x; // pointer S is now pointing to memory location of x
S = 4;
OR
x = 4; // changes the contents of memory location to which S points`
cout << *S; // displays the memory address to which S points i.e.
x
Related
Not sure how I was supposed to formulate the title.
I'm writing a program that asks for a students name, and if the name is not "stop", then it asks for a course name. If the course name is not "stop", it asks for a grade, then returns to ask for another course until the course name is "stop". Then it asks for another student and does the whole thing again until the student name is "stop". Then it prints all the students with their courses and grades.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
struct student{
public:
string name;
string course;
int grade;
}student_t;
void input(){
cout << "Please type the name of a student: " << endl;
getline(cin, student_t.name[i]);
if (student_t.name.compare("stop")){
break;
}
else {
cout << "Please type a course name: " << endl;
getline(cin, student_t.course);
if (student_t.course.compare("stop")) {
break;
}
else {
cout << "Please type the grade: " << endl;
cin >> student_t.grade;
}
}
}
int main() {
int i;
vector<student> input(i);
for (i = 0; i < 20; ++i){
student[i].input();
}
cout << student_t.name << " - " << student_t.course << " - " << student_t.grade << endl;
return 0;
}
It does not work at all..
I'm new to C++ so I dont really know why.
Any ideas?
I can give one or two recommendations.
Instead of checking if every step is wrong (i.e. equals "stop"), focus on what is right (i.e. what's the next things to read). From a mental perspective, I find it much easier to think about what has to be right for the program to progress as intended, as opposed to "What can go wrong here?" at every step. Your input() could then be (in pseudo code):
if (student_t.name is not "stop")
{
Read_course_name();
if (student_t.course is not "stop")
{
Read_grades();
// Done
return(StudentInfo);
}
}
// Ending up here means "stop" was typed so deal with that
// in a meaningful way
...
Take a look at https://en.wikipedia.org/wiki/Separation_of_concerns and then ask yourself, -Is the input() function really an input or are there more than one concern that coud be broken out in a separate function?
Cheers
/N
I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third.
#include <iostream>
using namespace std;
int main()
{
char first_name;
cout << "Please enter a name: ";
cin >> first_name;
cout << first_name << endl;
char second_name;
cout << "Please enter a name: ";
cin >> second_name;
cout << second_name << endl;
char third_name;
cout << "Please enter a name: ";
cin >> third_name;
cout << third_name << endl;
return 0;
}
You should probably be using string in your code to take the input of names. In names you are probably passing more than one character. The first one is read by first_name and any further character will be read by the following character, specifically cin>>second_name and cin>>third_name would read the 2nd and 3rd character of your input.
char a;
char b;
cin>>a; //will only read one character and stop
cin>>b; //will read the second character of the input...
//be that after pressing enter(a Enter b) or continuous input (ab)
cout<<a<<" "<<b; //will output 1st and 2nd character only
This will happen even if you don't press the Enter key explicitly and this is why your program uses the answer of first question(which is probably more than 1 character since it is a name) in your code as the answer to 2nd and 3rd questions as well.
So for your purpose, you are better of using string to take input from the users.
Hope this clears your doubt !
You tried to hold a lot of chars (one word) in one char who can hold only one char.
#include <iostream>
#include <string> // We need a string, container to hold a chars. Something like array of chars but have a few difference.
using namespace std; // You should avoid using this but in that short code this doesn't matter
int main()
{
// You don't need separate container for this code
// Then we create one container to holds all of inputs
string input;
cout << "Please enter a name: ";
cin >> input; // Put input from user in our input(string)
cout << input << endl; // Print input
// Next code is the same as above
cout << "Please enter a name: ";
cin >> input;
cout << input << endl;
cout << "Please enter a name: ";
cin >> input;
cout << input << endl;
return 0;
}
I special avoided a few elements like using function because this must be simple as possible.
I've made an addDepartment function that takes a structure as an argument. When I enter input to initialize the "dept[counter].departmentHead" at the bottom of the function, it triggers the error message.
I'm copying the logic from another code I wrote using classes instead of structures and that one works fine so I'm really not sure why this one isn't working. Tried messing with the index to make sure I wasn't going over the size of the array but that doesn't seem to fix the issue.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;
struct Department{
string departmentName;
string departmentHead;
int departmentID;
double departmentSalary;
};
//...
Department addDepartment(Department dept[3]){
int repeat=0;
int counter=0;
if (counter>2){
cout<<"The array is full, you can not add any more Departments."<<endl;
}
else{
cout << "Please Enter Department Details:"<<endl;
cout << "Department ID : ";
cin >> dept[counter].departmentID;
for(int x=0; x<3; x++){
for (int y=x+1; y<3; y++){
if(dept[x].departmentID==dept[y].departmentID)
repeat++;
}
}
if(repeat!=0)
cout<<"Value must be unique!"<<endl;
else{
cout << "Department Name : ";
cin >> dept[counter].departmentName;
cout << "Head of Department : ";
cin >> dept[counter].departmentHead;
counter++;
}
}
}
//...
int main()
{
Employee emp[5];
Department dept[3];
initialID(emp,dept,0);
initialID(emp,dept,1);
int response;
while(response!=6){
displayMenu();
cout<< "Please make a selection : \n";
cin >> response;
while((response!=1)&&(response!=2)&&(response!=3)&&(response!=4)&&(response!=5)&&(response!=6)){
cout<< "Please enter a valid choice (1 - 6): ";
cin >> response;
}
if(response==1){
addDepartment(dept);
}
else if(response==2){
//addEmployee(emp,dept);
}
else if(response==3){
}
else if(response==4){
}
else if(response==5){
//salaryReport(dept);
}
}
cout << "Thank you, goodbye.";
}
Why it breaks.
The addDepartment function never actually returns a department. When the function exits, the space where the return newly created Department would be is left uninitialized. This causes undefined behavior. The compiler tries to destruct the Department object like it normally would, but because it was never initialized, free gets called on garbage (causing the error).
We can fix this by adding a line to addDepartment returning the actual department:
Department addDepartment(Department dept[3]){
int repeat=0;
int counter=0;
if (counter>2){
cout<<"The array is full, you can not add any more Departments."<<endl;
}
else{
cout << "Please Enter Department Details:"<<endl;
cout << "Department ID : ";
cin >> dept[counter].departmentID;
for(int x=0; x<3; x++){
for (int y=x+1; y<3; y++){
if(dept[x].departmentID==dept[y].departmentID)
repeat++;
}
}
if(repeat!=0)
cout<<"Value must be unique!"<<endl;
else{
cout << "Department Name : ";
cin >> dept[counter].departmentName;
cout << "Head of Department : ";
cin >> dept[counter].departmentHead;
counter++;
}
}
return /* some department */;
}
Alternatively, you could make addDepartment void.
Other considerations. Don't pass raw C arrays to functions. It doesn't do what you intend.
If you want to pass a copy of an array, pass a std::array, which will be copied automatically:
Department addDepartment(std::array<Department, 3> dept);
If want to access the elements of an existing array, pass a pointer:
Department addDepartment(Department* dept, int count);
One problem that I see is that you are creating an array of 3 Department objects in main and assuming that you have 5 elements in initialID.
Change main to create an array of 5 Department objects.
int main()
{
Employee emp[5];
Department dept[5];
...
Consider the following code:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
class treasure
{
public:
char name[100];
double value[100];
double weight[100];
};
int itemNumber, totalWeight, i;
treasure item;
std::cout << "Enter total item weight: " << std::endl;
std::cin >> totalWeight;
std::cout << "Enter total item number: " << std::endl;
std::cin >> itemNumber;
for( i = 0; i < itemNumber; i++)
{
std::cout << "Enter item name: " << std::endl;
std::cin >> item.name[i];
}
return 0;
}
I wanted to input 5 item in the array but it is just asking for two item. It takes one item at first and then after printing three lines again takes another input. What seems to be the problem. What did went wrong?
char name[100]; means that you can save up to 100 items of type char, not 100 strings.
An important effect here is that your input is buffered. std::cin >> item.name[i]; takes one char from the input buffer and writes it to name[i]. The rest of your input remains in the buffer and will be used for the next execution of cin, i.e. the next execution of the same code line.
So if you enter e.g. 'abc' it saves 'a' to item.name[0], 'b' to item.name[1] and 'c' to item.name[2]. For item.name[3] the input buffer is empty so it waits for your next input.
I have a C++ project to do for my class and it's quite intricate, to me at least. I've got the general idea and concept down, but i'm running into some other problems when it comes to the arrays and file stuff. Below is what the project consists of
You will be building and modifying a class roster system for a Teacher to manage his class roster and their final grades. This program
will use functions for the various menu options, and you will work with
the data in arrays or vectors. The program will provide a menu system that allows for the teacher to perform tasks until he chooses to close the program. The program will read and write to a file called
classroster.txt. Any and all additions, deletions, or changes to the roster will be saved in classroster.txt file.
This file will contain the names of each of the students in the class with their grade. See the following for an example listed below of how the data would be stored in the classroster.txt file. You should work with the data using arrays or vectors.
Jim Jones C
Kevin James B
Marc Cohen A+
When the program starts it should read the data from the classroster.txt into arrays or vectors. While the program is running it should use the arrays or vectors for the functions while using the program. When the program ends it should overwrite the classroster.txt file if something has been changed. The
programs menu will offer the following options and will allow the user to keep performing functions until they choose to exit the program ( hint !!!!! you will need to use a loop for the menu system)
Add A New Student-
This will allow the user to add a new student to the system. The system should prompt for the new students full name and then grade.
It should validate that the grade is in the following values
(A+, A, A-, B+, B, B-,C+,C, C-, D+, D, D-, F) and if not
in the approved list it should prompt the user for a valid grade.
Change a Students Grade-
This will find the student in question and change the grade. If the specified student doesn’t exist the program should print an error message telling the user that you couldn’t find the specified student to
change their grade.
Remove a Student-
Will remove a student and their grade from the roster. If the specified student doesn’t exist the program should print an error message telling the user that you couldn’t find the specified student to remove.
Display Class Roster–
(Bonus Points if you can display the names is alphabetical order) This
function will display the list of all the students and their grades on
the screen that looks like this:
Student Name Grade
Jim Jones C
Kevin James B-
Marc Cohen A+
This is what i have so far, it's obviously not done yet
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
const int num_of_students;
const int new_student = 1, change_grade = 2, remove_student = 3, display_roster = 4, quit = 5;
int classroster[num_of_students];
int student_grade[num_of_students];
string possible_grades[13] = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"};
int choice;
ofstream class_file;
cout << "How many students do you have in your class?" << endl;
cin >> num_of_students;
cout << "---MENU---" << endl;
cout << "1. Add A New Student" << endl;
cout << "2. Change A Students Grade" << endl;
cout << "3. Remove A Student" << endl;
cout << "4. Display Class Roster" << endl;
cout << "5. Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == new_student) {
for (int index = 0; index < num_of_students; index++) {
class_file.open("classroster.txt");
cout << "What is the name of the student you want to add? ";
getline(cin, classroster);
if (student_grade == possible_grades) {
cout << "What is the final grade of this student? ";
getline(cin, student_grade);
}
else {
"Please enter a valid grade!"
}
cout << "Student added!";
}
}
else if (choice == change_grade) {
class_file.open("classroster.txt");
cout << "What is the name of the student whose grade you want to change? ";
getline(cin, )
}
else if (choice == remove_student) {
}
else if (choice == display_roster) {
}
else if (choice == quit) {
}
else {
cout << "Please enter a valid choice!"
}
system("PAUSE");
return 0;
}
First, to answer your question, here's one way to search an array of student names:
int index = -1;
for(int k=0; k<num_of_students; ++k)
{
if(names[k] == name)
index = k;
}
And here's a way to change the array of grades:
student_grade[index] = 3;
More generally, you taking the wrong approach. Your code does not compile, so it looks as if you're writing it all out before testing any of it. As they never seem to teach in school, you should start with something small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work.
Let's start with the number of students:
int main() {
const int num_of_students;
cout << "How many students do you have in your class?" << endl;
cin >> num_of_students;
return(0);
}
Try to compile this, and you'll find that there's something wrong. Fix it and try constructing an array of int and filling it in. Once that's working, try an array of string. Small steps.
You realy should be using maps for this question, its makes the most sense. Here is code to read in the map from a file. After you have the map all the operations you need are already implemented in the STL. I realize you may need to use vector but I'd like to think you wouldn't be penalized for being clever and actually writing a proper solution.
#include <map>
#include <fstream>
#include <iostream>
using namespace std;
int main(){
map<string,string> data;
fstream fs("classroster.txt");
while(fs.good()){
string fname, lname, grade;
fs >> fname;
fs >> lname
fs >> grade;
fname += lname; //Concat Names to get full
if(grade == "A") //Check other grades as well.
data.emplace(fname,grade);
}
while(1){
string option;
std::cout << "Options:" << endl;
cin >> option;
//Your option selection code here
}
return 0;
}
EDIT:
maps are also sorted by key name so printing alphabetically is very easy, no sorting required.
for(auto& pairs : data)
cout << pairs.first << " " << pairs.second << endl;