This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 4 years ago.
Im using fgets(learner.name,21,stdin) to Input the name of the student but when i run the program ,it shows " Enter your name " and skips to "Enter your marks in 5 subjects. "
can someone explain me why this happening?Because it is same with cin.getline() function.
gets_s() function is not working compiler shows " 'gets_s' was not declared in this scope"
#include<iostream>
#include<stdio.h>
#include<cstdlib>
using namespace std;
struct Student
{
int rollno;
char name[21];
float marks[5];
char grade;
};
Student learner ;
int main()
{
cout<<"\n"<<"Enter Roll number: ";
cin>>learner.rollno;
cout<<"\n"<<"Enter your name: ";
fgets(learner.name,21,stdin);
cout<<"\n"<<"Enter your marks in 5 subjects: "<<"\n";
for(int i = 0;i <5;++i)
{
cout<<"\n"<<"Subject"<<i+1<<":";
cin>>learner.marks[i];
}
float avg ,total;
total = (learner.marks[0]+learner.marks[1]+learner.marks[2]+learner.marks[3]+learner.marks[4]);
avg = total/5;
if(avg<50)
learner.grade = 'D';
else if(avg<60)
learner.grade = 'C';
else if(avg<80)
learner.grade = 'B';
else
learner.grade = 'A';
cout<<"\n"<<"\n"<<"Student result: \n";
cout<<"Roll Number: "<<learner.rollno<<"\t";
cout<<"Name: ";
cout.write(learner.name,21);
cout<<"\n"<<"Total Marks: "<<total;
cout<<"\t"<<"Grade: "<<learner.grade<<endl;
system("pause");
return 0;
}
here is the output:
Enter Roll number: 22
Enter your name:
Enter your marks in 5 subjects:
Subject1:
The reason is that when you type roll no and press enter, cin only reads the number, not the newline (this is the default behaviour.). This newline remains in the input stream and when you execute fgets(), it takes in the newline character.
To change this you could use cin >> noskipws >> learner.rollno;
stdin buffer is not cleared after cin>>learner.rollno;, use getchar() to clear/flush the stdin buffer and then use cin.getline() as
cin.getline(learner.name,'\n');
Related
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 2 years ago.
Im a new user of c++ and I am stuck with a problem.
If the input for the int variable 'x' is anything other than a number, then c++ seems to skip the cin associated with the char variable 'y'. I tried to use cin.ignore and cin.clear, but they dont seem to work. Any ideas on how to make the program still ask the value for char 'y' when the value for int 'x' is anything but a number(eg. 'a' '*' '') ?
#include <iostream>
using namespace std;
int main()
{
int x;
char y;
cout << "num: ";
cin >> x;//int input
cout << endl;//blank line
cout << "char: ";
cin >> y;//char input
cout << endl;//blank line
return 0;
}
Are you passing parameters to ignore?
The first parameter is the maximum of chars to be ignored and the second one is the flag that it should stop ignoring after findind it (which in the example below I've put '\n')
cin.clear();
cin.ignore(1000, '\n');
To summarize, the code says: Clear up to 1000 chars or up to the first '\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.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Using getline() in C++
(7 answers)
Closed 4 years ago.
Can anyone explain why I am having trouble with the below C++ code?
#include <iostream>
using namespace std;
class stud
{
public:
string name,adrs;
long long unsigned int mob;
};
int main()
{
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
for(int i = 0; i < num; i++)
{
cout << endl << "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin, s[i].name); // this line skips some data before even they are
//entered and there is no error while compiling
}
system("CLS");
for(int i = 0; i < num; i++)
{
cout << endl << " Student " << i+1 << " name is: ";
cout << s[i].name << endl;
}
return 0;
}
When I try to input a string value for an object in the array as above, using getline() without any delimiter (which uses a new line by default), I don't get correct output since some other data is automatically being skipped.
But, when I use getline() as follows instead of above, it works fine, but it needs a delimiter at the end:
getline(cin, s[i].name, '.');
Please help me find a solution. I think the Enter key is pressed several times at one key press, and that's why the getline() skips some data. I'm not sure about this, though.
before correcting you program one thing to know is that
Actually, a newline is always appended to your input when you select Enter or Return when submitting from a terminal.
cin>> doesn't remove new lines from the buffer when the user presses Enter.
This has little to do with the input you provided yourself but rather with the default behaviour std::getline() exhibits. When you provided your input for the name (std::cin >> num;), you not only submitted the following characters, but also an implicit newline was appended to the stream, getline() mistakes this for user input along with enter.
It is recommended to use cin.ignore() to get rid of those extra characters after using cin>>(whatever) if you are going to use getline(cin,any string) later.
Edit this part of your code:
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
cin.ignore();//just add this line in your program after getting num value through cin
//fflush(stdin);
//cin.sync();
//getchar();
for(int i = 0; i < num; i++)
{
cout<<endl<< "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin,s[i].name);
}
system("CLS");
you can use and may be tempted to use fflush(stdin) also but it is not recommended as it has undefined behaviour, as
According to the standard, fflush can only be used with output buffers, and obviously stdin isn't one.
about cin.sync():
using “cin.sync()” after the “cin” statement discards all that is left in buffer. Though “cin.sync()” does not work in all implementations (According to C++11 and above standards).
you can also use getchar() to get the newline caused by Enter
This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
I need to use getline to store whole line when user enters name and surname. When I run the program, it passes row of getline(cin,st[i].name); I mean the input function does not work, it skips next cin which is for "score".
struct Student {
string name;
int score;
char grade;
};
void main() {
int SIZE;
cout << " How many students are you going to add ? ";
cin >> SIZE;
Student* st = new Student[SIZE]; // user determines size of array.
int i;
for (i = 0; i < SIZE; i++)
{
if (st[i].name.empty()) // if array list of name is empty, take input.
{
cout << "name and surname : ";
//cin >> st[i].name;
getline(cin, st[i].name);
}
cout << "Score : ";
cin >> st[i].score; // take quiz score from user.
-- I did not put whole main function.
So when l run the program, back screen is shown
Is there any other way to get input for name ?
After cin >> SIZE;, the trailing newline is still kept in standard input.
You need cin.ignore() to skip the remaining newline character so the later getline() could get the value.
This question already has answers here:
Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]
(4 answers)
Closed 7 years ago.
I'm trying to validate the user inputs. If the user inputs anything but an integer it should stay in the While loop. But when I give the program a "w" for instance the program just endlessly prints "Please input integer" and I have to stop the program.
int MAns1 = 0
while (!(cin >> MAns1))
{
cout << "\nPlease Enter An Integer: ";
cin.clear();
}
Because you should be testing (cin >> MAns1), not !(cin >> MAns1). I would do something like this though:
#include<iostream>
using std::cin;
using std::cout;
int main() {
int MAns1 = 0;
for (;;)
{
cout << "\nPlease Enter An Integer: ";
cin >> MAnsi;
// did the last read succeed?
if(!cin) {
// it did *not* succeed.
break;
}
}
}