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.
Related
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 ;)
I new to programming and was trying to implement struct program in c++, it's simple program but it's not printing proper result. please tell me why?
#include <iostream>
using namespace std;
struct classroom {
int number;
char name[9];
int marks;
void getAndPrint()
{
cout << "struct classroom ";
cin >> number;
cout << number << '\n';
cin.get(name, 9);
//cin>>name;
cout << name;
cin >> marks;
cout << marks;
}
};
int main()
{
classroom room1;
room1.getAndPrint();
int i;
cin >> i;
return 0;
}
In function getAndPrint() I'm using cin.get()..the compiler execute the properly till printing the "number" but when it comes on cin.get(name,9) it print garbage and skips the rest of the code inside the funcion. If i use cin>>name then it's working properly.
Can anyone tell what exactly is the problem?
first, in C++, struct is class with access_modifier is public.
second, you should try read:
Difference between cin and cin.get() for char array
The structure definition does not contain such a function like see
room1.see();
^^^^
I think you mean
room1.getAndPrint();
Also before this statement
cin.get(name, 9);
insert at least this statement
cin.ignore();
Or you even can include the header <limits> and insert statement
#include <limits>
//...
cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
I've recently started teaching myself C++, and after having written a lot of user input code, it's made me wonder if there's a simpler way of handling it.
For example, the normal way of doing it would be like this:
#include <iostream>
using namespace std;
int inp;
int guess = 13;
void main(){
cout << "Guess a number: ";
cin >> inp;
if (inp == guess)
cout << endl << "Nice.";
}
But what I want to do is:
#include <iostream>
using namespace std;
int guess = 13;
void main(){
cout << "Guess a number: ";
if (cin == guess)
cout << endl << "Even nicer.";
}
Is there a way to do this? Or this that just improper C++ standard?
In short: No, it's not possible to do as you want it.
You need to understand, that >> is actually a function call of
template<typename T>
std::istream& operator>>(std::istream& is, T& result);
and == is a function call to
template<typename T>
bool operator==(const std::istream&,const T& x);
Where the latter is used to check the stream state, and doesn't extract any user input.
To compare the input the result needs to be extracted from the std::istream in 1st place.
Well you can do it in one line but you don't really need to. But here are some examples anyway
//This will work for a char
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char test = 'a';
if (getch()== test)
cout<<"\n Works";
return 0;
}
And if you really want
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x =1;
int y;
for( cin >> y ; x == y ; )
{
cout<<"\n Works";
break;
}
return 0;
}
Or as NathanOliver said you could simply do this
if( cin >> inp && inp == guess )
But really you want to keep it simple as this will confuse others as well as yourself after some time. You want to leave your code as easy as possible
Hey the code is running fine without any errors but it just jumps to return 0.
I would also like to note that I'm kind of new to c++ and i just started using classes.
Thanks for the help!
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class List{
public:
void SetNote(string Note){
Notepp = Note;
}
string getNotepp(){
return Notepp;
}
private:
string Notepp;
};
int main(){
string x;
cin >> x;
List LisObj;
LisObj.SetNote("Exit Notepad++.exe");
if(LisObj.getNotepp() == x){
cout << "Hello World\n";
}
return 0;
}
because you use "cin>>" to get a string!That is not possible,use "getline" instead,"cin" takes a blank to determine which part to get,for example:when you enter the sentence:"Exit Notepad++.exe",what your "x" get is just a "Exit",due to the blank after.The main function should be like this:
int main()
{
string x;
getline(cin,x);
List LisObj;
LisObj.SetNote("Exit Notepad++.exe");
if(LisObj.getNotepp() == x)
{
cout << "Hello World\n";
}
return 0;
}
If you want to print "hello world": You may do:
int main(){
string x;
cin >> x;
List LisObj;
LisObj.SetNote(x);
if(LisObj.getNotepp() == x){
cout << "Hello World\n";
}
return 0;
}
Now if you want to print hello world only when user enters "Exit Notepad++.exe". Do not do like:
cin>>x;
as you input may contain space. Rather use getline() or cin.getline()
When you input a string with spaces using cin >> when it reaches a space it will assume that it's the end of the input.
To get round this we use getline() or cin.getline()
Also instead of using Return 0; use :
cin.sync();
cin.ignore();
as in some cases return 0;
does not prevent the terminal from closing.
I want to declare two types of variables in for's init-statement. like the following codes. I know "for (string word, int numb, ; cin>>word>>numb; )" is not working. just trying to let you know what I am trying to do. My goal is to declare two types of variables with the same lifetime and cin them together. Other way of coding is helpful too. thanks in advance.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
cout<<"enter a word and a number"<<endl;
for (string word, int numb, ; cin>>word>>numb; )
{
//do some work
}
return 0;
}
ok, I think this is the closest I can get as someone suggested.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
vector<pair<string,int> > pvec;
cout<<"enter a word and a number"<<endl;
{
int numb=0;
for (string word; cin>>word>>numb; )
pvec.push_back(make_pair(word,numb));
}
cout<<pvec[3].second<<endl;
return 0;
}
About the nearest you can get is:
int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
for (int numb; cin>>word>>numb; )
{
//do some work
}
}
return 0;
}
The extra set of braces limits the scope of word similarly to the way the loop limits the scope of numb. Clearly, you could reverse the declarations; it might be better (more symmetric) to use:
int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
int numb;
while (cin>>word>>numb)
{
//do some work
}
}
return 0;
}
Since there is no increment or initialize operation, the code is really a while loop with a couple of declared variables; this achieves the same result and works.
This is not possible. You can declare two variables of the same basic type in the initialization statement in the for loop, but you cannot declare two variables of different basic types. You have to declare one outside of the for loop.
I'm fairly certain it's not possible to declare 2 variables of 2 different types in a for statement, but I also fail to see the advantage to doing so over something like this:
int main ()
{
cout<<"enter a word and a number"<<endl;
while( cin.good() )
{
string word;
int num;
cin >> word >> num;
//do some work
}
return 0;
}
In general I prefer to use for loops where there is something to count or at least iterate over. Other situations should be using a while or do loop.
The way you are trying to do it is not the cleanest way. I'd do it like this:
string word;
int num;
while(true)
{
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
word and num are in the same scope (same "lifetime")
Note that you'd want to substitute the while(true) with some suitable condition.
If you want word and num to be inside the scope of the loop do something like:
while(true)
{
string word;
int num;
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
OR
{
string word;
int num;
while(true)
{
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
}
I don't know why this would be necessary though.
The following is untested, but should work:
int main()
{
std::cout << "enter a word and a number" << endl;
for (struct { std::string word, int number } vars;
std::cin >> vars.word >> vars.number;
)
{
//do some work
}
return 0;
}
Since c++17:
#include <iostream>
#include <tuple>
int main() {
for (auto && [w,i] = std::tuple{std::string{},int{}} ; std::cin >> w >> i ; )
std::cout << "word " << w << " number " << i << "\n";
return 0;
}