The code below,works fine but it does not take any value for age and terminates.`
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
char name[20],server[40];
public:
void get(){
cout<<"Enter your name:";
cin>>name[20];
cout<<"Enter your age:";
cin>>age;
}
};
int main(){
user u;
u.get();
return 0;
}
/*Output
Enter your name:Jack
Enter your age:
C:\Users\user\documents\c++
*/
In the output section ,age is not accepted and the program terminates.
Use string name instead of char name[20] to take multi-character value. char name[20] will terminate after taking a single character.
Also, its valued will not be displayed on giving output.
Modified code for reference.
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
string name,server;
public:
void get(){
cout<<"Enter your name:";
cin>>name;
cout<<"Enter your age:";
cin>>age;
}
//test output
void put(){
cout<<name<<endl;
cout<<age<<endl;
}
};
int main(){
user u;
u.get();
//test
u.put();
return 0;
}
Just modify the code to this :
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
char name[20],server[40];
public:
void get(){
cout<<"Enter your name:";
cin>>name; // changes done here
cout<<"Enter your age:";
cin>>age;
}
};
int main(){
user u;
u.get();
return 0;
}
Job Done :)
Your problem is here:
cin>>name[20];
Why:
'name[20]' is 21th char of the array you defined before. It counts from 0! As this, it is simply a single char. If you now enter more than a single char, the rest is read by the cin>>age.
Example:
cout<<"Enter your name:";
cin>>name[20];
cout<<"Enter your age:";
cin>>age;
std::cout << "Name " << name << std::endl;
std::cout << "Age " << age << std::endl;
And entering:
Enter your name:1234
Enter your age:Name
Age 234
As you see, the '1' is now in the name and the rest is stored in age.
But attention: You defined your array as `name[20], which means you have 0..19 elements. Accessing name[20] is wrong!
But what you simply want to do was:
cin >> name;
The easiest way to handle strings (a long sequence of characters) or even the strings that have spaces just use the following library in C++.
#include <bits/stdc++.h>
Then just declare a string variable.
String name;
Now you can save a very long string without any error. e.g.
name = jshkad skshdur kslsjue djsdf2341;
and you'll get no error, enjoy ;)
Related
I'm trying to build a beginner employee database program.
Here is the problem; when counter "i" in main() becomes "1", the 1st line of the loop is skipped; in the other words, it doesn't wait for user to enter the value for "name" string. When I use "cin" rather than "gets" there is no problem...Why this is so? I use ubuntu 16.04.
#include <iostream>
#include <cstdio>
using namespace std;
void enter();
void report();
char name[2][30],salary[2][30];
int main()
{
int i;
for(i=0;i<2;i++){
cout<< "Name:"<<'\n';
gets(name[i]);
cout<< "Salary:"<<'\n'; cin>>(salary[i]);
}
report();
return 0;
}
void report()
{
int i;
cout<<"Name"<<'\t'<<"Salary"<<'\n';
for(i=0;i<2;i++){
cout<< name[i]<<'\t'<<salary[i]<<'\n';
}
}
Instead of using gets(), I would recommend using either std::cin >> name[i]; or cin.getline(name[i], 30);. The latter will fetch spaces.
You will then need a cin.ignore(); after the cin >> salary[i]; because of the extra return character that fills the buffer.
I am C++ noob, forgive me if this a simple question, I have been trying to solve this problem since past couple of days.
There exists a class called student which stores names, age and marks of a student. Each student's profile (age, name and marks is stored in a class). There are n students in a class hence , a vector<student*> is created, which stores the pointers to all the students profile in a class.
I want to print the values stored in the `vector I would really appreciate any hints!
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
class student{
private:
string name;
float marks;
int age;
public:
student(): name("Null"), marks(0),age(0){}
student(string n, float m,int a): name(n), marks(m),age(a){}
void set_name();
void set_marks();
void set_age();
void get_name();
void get_marks();
void get_age();
};
void student::set_name(){
cout<<"Enter the name: ";
cin >> name;
}
void student::set_age(){
cout << "Enter the age: ";
cin >> age;
}
void student::set_marks(){
cout<<"Enter the marks ";
cin>> marks;
}
void student::get_name(){
cout<<"Name: "<< name<<endl;
}
void student::get_age(){
cout<<"Age: "<< age<<endl;
}
void student::get_marks(){
cout<<"Marks: "<< marks<<endl;
}
int main() {
int n;
cout<<"Enter the number of students: ";
cin >> n;
vector <student*> library_stnd(n);
for(int i=0;i<n;i++){
student* temp = new student;
temp->set_name();
temp->set_age();
temp->set_marks();
library_stnd.push_back(temp);
}
for (auto ep: library_stnd){
ep->get_age();
}
return(0);
}
vector <student*> library_stnd(n) create a vector of size n. Then in the first for loop library_stnd.push_back(temp) push temp to the end of library_stnd and does not change first n items.
The problem is the first n items in library_stnd is zero initialized[1] and dereferencing it in the second for loop is an undefined behavior.[2]
My suggestions is using either one of the following:
vector <student*> library_stnd and library_stnd.push_back(temp)
vector <student*> library_stnd(n) and library_stnd[i] = temp
Another suggestion
vector<student> instead of vector<*student>, then for (auto& ep: library_stnd)
'\n' instead of endl [3]
double instead of float [4]
[1] - What is the default constructor for C++ pointer?
[2] - C++ standard: dereferencing NULL pointer to get a reference?
[3] - C++: "std::endl" vs "\n"
[4] - https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double
this code is working fine for first instance but for second instance it is not working
input :
poorva
17
26
raju
18
28
for second object i.e raju it is not taking name and roll no and shows some garbage value here is the ideone link https://ideone.com/uxwMAc
#include<bits/stdc++.h>
using namespace std;
class student
{
int roll;
int age;
char name[20];
public:
void getData();
void showData();
};
void student::getData()
{
char n[20];
int a,r;
cout<<"enter name of student \n";
gets(name);
cout<<"enter age of student \n";
cin>>age;
cout<<"enter roll no of student \n";
cin>>roll;
}
void student::showData()
{
cout<<"details are \n\n";
cout<<"name is :";
puts(name);
cout<<"age is "<<age<<endl;
cout<<"roll number is "<<roll<<endl;
}
int main()
{
student poorva ;
student raju ;
//for poorva
poorva.getData();
poorva.showData();
//for raju
raju.getData();
raju.showData();
return 0;
}
puts and gets are C-derived functions from <cstdio>. cin and cout are C++ streams from <iostream>. Don't mix them, they interact badly when they both read from (or write to) the same underlying stream without co-ordinating.
Try using cin.getline instead, and remove puts entirely. Ideally replace your fixed character array with std::string too.
Oh, and don't #include<bits/stdc++.h>. That's an implementation detail. Wherever you got the idea that it's reasonable to use this directly, is a bad place to learn C++ and you should stop using it (and maybe name & shame it here).
Your code should probably begin with
#include <iostream>
instead.
Tey the following
Student raju =new Student () ;
Though that should have worked.
Same with pooja
I'm doing an assignment which requires file handling in C++.Assignment is long enough to be posted here, but i have made a similar simple code to elaborate my question.The following code is not read all data from file it only read the last record
please help me to make it correct.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string.h>
//class
class medicine{
int id;
char med_name[50];
int price;
int quantity;
char date[50];
public:
void data_entery(){
//int i;char na[50];int p;int q;char da[50];
cout<<"Enter id: ";
cin>>id;
cout<<"Enter name: ";
cin>>med_name;
cout<<"Enter price: ";
cin>>price;
cout<<"Enter quantity: ";
cin>>quantity;
cout<<"Enter exp_date: ";
cin>>date;
}
void display(){
cout<<this->id<<"\t "<<this->med_name<<"\t "<<this->price<<"\t"<<this- >quantity<<"\t "<<this->date;
}
}med[10];
using namespace std;
int main (){
//writing in file
ofstream wfile("medicines.txt",ios::app|ios::binary);
wfile.seekp(0,ios::end);
int rec=wfile.tellp()/sizeof(medicine);
cout<<"there are "<<rec<<" records";
med[rec].data_entery();
wfile.write(reinterpret_cast<char *>(&med),sizeof(medicine));
wfile.close();
//reading in file
ifstream rfile("medicines.txt",ios::in|ios::binary);
rfile.seekg(0,ios::end);
rec=rfile.tellg()/sizeof(medicine);
rfile.seekg(0,ios::beg);
cout<<"there are "<<rec<<" records";
for (int k=0;k<rec;k++){
med[k].display();
}
rfile.read(reinterpret_cast<char *>(&med),sizeof(med)*rec);
rfile.close();
getch();
return 0;
}
I am assuming that your file medicines.txt is initially empty.
What you have done wrong is that you have made 10 objects of the medicine class, but you are writing only one object to the file.
What you need to do here is:
for (int i=0; i < 10; i++) {
med[i].data_entery();
wfile.write(reinterpret_cast<char *>(&med),sizeof(medicine));
}
wfile.close();
Now you'll need to add 10 medicines, after details of each medicine has been added, that medicine will be written to the file.
I hope this helps.
Here is a better version of your code
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string.h>
using namespace std;
//class
class medicine
{
int id;
char med_name[50];
int price;
int quantity;
char date[50];
public:
void data_entery()
{
//int i;char na[50];int p;int q;char da[50];
cout<<"\nEnter id: ";
cin>>id;
cout<<"Enter name: ";
cin>>med_name;
cout<<"Enter price: ";
cin>>price;
cout<<"Enter quantity: ";
cin>>quantity;
cout<<"Enter exp_date: ";
cin>>date;
}
void display()
{
cout<<"\nID :"<<this->id<<"\nName :"<<this->med_name<<"\nPrice :"<<this->price<<"\nQuantity :"<<this->quantity<<"\nExp Date :"<<this->date<<"\n";
}
}med;
int main ()
{
//writing in file
ofstream wfile("medicines.txt",ios::app|ios::binary);
wfile.seekp(0,ios::end);
int rec=wfile.tellp()/sizeof(medicine);
cout<<"\nthere are "<<rec<<" records";
med.data_entery();
wfile.write(reinterpret_cast<char *>(&med),sizeof(medicine));
wfile.close();
//reading in file
ifstream rfile("medicines.txt",ios::in|ios::binary);
rfile.seekg(0,ios::end);
rec=rfile.tellg()/sizeof(medicine);
rfile.seekg(0,ios::beg);
cout<<"\nthere are "<<rec<<" records";
while(rfile.read(reinterpret_cast<char *>(&med),sizeof(med)))
{
med.display();
}
rfile.close();
getch();
return 0;
}
Now, when you are using files, you do not need to create an array of objects. Once you store the object into the file, you can just reuse that object. The data can be accessed from the File. That is what I have done in this code. I have edited this code in such a manner as to not change your method, instead just corrected the problems and also made your code a little better. In each run of this code, you enter the details of one record, and then the details of all the records are shown.
The good thing about this code is, you can enter as many records as you want. You are not restricted to 10 records like your original code.
I'm having an issue with my simple Hello World code.
I'm not able to cin my name. It says no defined operator ">>" Can someone help please. Below is my code.
#include <iostream>
using namespace std;
int main()
{
int x;
string name;
cout<< "enter name:";
cin>> name;
cout<< "Hello "<< name <<endl;
system("Pause");
}
You have to
#include <string>.