This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is this a bug with getline(), or am I doing something wrong. Right way to use getline()?
I tried to learn this topic on STL lists and Strings. So as an integration, i tried out this program:
#include<iostream>
#include<list>
#include<string>
using namespace std;
int main(){
list<string> obj1, obj2;
string obj;
int n;
cout<<"Enter the number of elements in string list 1:\t";
cin>>n;
cin.clear();
cout<<"Enter the string:\n";
for( int i=0; i<n; i++){
getline(cin, obj);
cout<<"The string is:\t"<<obj<<" and i is "<<i<<endl;
obj1.push_back(obj);
}
obj1.sort();
cout<<"The string in sorted order is:\n";
list<string>::reverse_iterator rit;
for( rit = obj1.rbegin(); rit != obj1.rend(); rit++)
cout<<*rit<<endl;
return 0;
}
I get the following output:
Enter the number of elements in string list 1: 4
Enter the string:
The string is: and i is 0
goat
The string is: goat and i is 1
boat
The string is: boat and i is 2
toad
The string is: toad and i is 3
The string in sorted order is:
toad
goat
boat
The error in the program is that the first string is a blank one that is automatically inserted into the list. In order to avoid this, i tried using cin.clear() but i am not able to overcome the error. Can anyone please identify the bug and help me with the answer.
One must take special care when using operator>> and getline in the same program. The operator>> leaves an end-of-line indicator in the input stream, which getline accepts.
Try adding std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') before the getline.
cin.clear() doesn't do what you think it does. Look it up. Then follow the advice that you got in Rob's answer.
It's because after you enter the number, the newline is still in the buffer, so the first getline gets that newline. The simplest solution is to use a dummy getline call before the loop.
Related
This question already has answers here:
C++: Why does space always terminate a string when read?
(4 answers)
Closed 2 years ago.
I wrote a code so that it removes everything(like spaces and other things) other than the alphabats using isalpha() function and converts it to lower case using tolower() function. It is working fine if i don't put a space in the string but if there is any space in the string then it go beyond the space. I dont understand why this is happening. This is the code i wrote.
#include<bits/stdc++.h>
#include<cstring>
#include<cctype>
using namespace std;
int main()
{
int i;
string A,b="";
cin>>A;
for(i=0;i<A.size();i++)
{
if(isalpha(A[i]))
b+= tolower(A[i]);
else
continue;
}
cout<<b;
}
Please help me.
Thankyou
The cin >> A; considers the space to terminate the input.
To get the whole line, use getline(cin, A);
cin reads the string till the first space it encounters, if your input string is "Hello World", then cin will only read "Hello".
You can use getline function to read a complete line.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 4 years ago.
#include<vector>
#include<iostream>
using namespace std;
int main(){
int number;
cin>>number;
string s1;
vector<string> lists;
for(int i=0;i<number;i++){
getline(cin,s1);
lists.push_back(s1);
}
for(int i=0;i<number;i++)
cout<<lists[i]<<" ";
}
When I enter 5 (for eg.) as input number, I am only able to enter 4 strings instead of 5. Can anyone help me out?
Thank you.
after the line cin>>number; there is still the newline character \n (because you pressed enter to input the value )in the input buffer, to fix this you add a line with cin.ignore();
int main(){
int number;
cin>>number;
cin.ignore(); // add this line
string s1;
vector<string> lists;
for(int i=0;i<number;i++){
getline(cin,s1);
lists.push_back(s1);
}
for(int i=0;i<number;i++)
cout<<lists[i]<<" ";
}
You are mixing line-based input (getline) and non-line-based input (cin>>number). This causes your first getline call to read an empty string into s1, because the \n in the stream has not yet been consumed.
So lists actually has 5 elements at the end, it's just that your output makes it hard to notice.
In order to prevent the problem, convert everything to line-based input instead. Replace this:
int number;
cin>>number;
With this:
std::string line;
std::getline(std::cin, line);
auto const number = std::stoi(line);
This is a superior solution anyway, because it makes it easier to detect wrong input (when the user enters something other than an integer number for number).
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 8 years ago.
Hi guys i am facing an unknown error while taking input from getline.My purpose is to take a number and two strings as input from the user and print the first string.Here is the problem code
#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{ string s,p;
getline(cin,s);
getline(cin,p);
cout<<s;
}
return 0;
}
Now when i give input like:
1
abababa abb
b
it doesn’t print anything.Why is it happening?
After cin>>t, there is a newline remaining in the stream, then the newline will be assigned to s, so cout<<s seems to print nothing(Actually, it prints a newline).
add cin.ignore(100, '\n'); before first getline to ingore the newline.
Each time you use cin to get something like in cin >> t, it will leave a newline in the input buffer. so in next operation it will be affected by that and will seem to skip the "wait for return key" and hence abnormality. To avoid that usecin::ignore.
the documentation says:
Extracts characters from the input sequence and discards them, until
either n characters have been extracted, or one compares equal to
delim.
The function also stops extracting characters if the end-of-file is
reached. If this is reached prematurely (before either extracting n
characters or finding delim), the function sets the eofbit flag.
I have written your code in very understandable way but working
Let me know if you have any issue
#include <iostream>
using namespace std;
int main() {
int t=0;
cout<<"Enter t\n";
cin>>t;
cin.ignore();
while(t>0)
{ string s,p;
cout<<"Enter s\n";
getline(cin,s);
cout<<"Enter p\n";
getline(cin,p);
cout<<" Values s:"<<s<<" p:"<<p<<"\n";
t--;
}
return 0;
}
The newline from cin >> t; after pressing enter is still in std::cin when getline(cin,s) is called, resulting in s being empty. The string you enter is actually being stored in p. Try using a different capture method or flushing the cin buffer before using it again.
I think it's because getline() doesn't ignore the new line ccharacter, but it reads it in the next call yo getline. Try yo put a getline() before each calle, something like this:
Int main() {
int t;
cin>>t;
string s,p;
getline(cin,s);
while(t--)
{
getline(cin,s);
getline(cin, p);
getline(cin,p);
cout<<s;
}
Hope it helps :)
Hello everyone I am doing a programming assignment on structured data and I believe I understand how structs work.
I am trying to read in a list of student names, ID numbers (A-Numbers), and their balances.
When I compile my code though, it will read everything in the first time around, but the second time around the loop and every time after, it prompts for the username but skips the getline and goes straight to A-Number and A-number entry.
Any help would be appreciated. Just trying to figure out how to make the getline work every time the loop goes around.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
const int maxStudents = 30;
struct Students{
string studentName;
int aNumber;
double outstandingBalance;};
Students students[maxStudents];
for(int count = 0; count < maxStudents-1; count++)
{
cout<<"Student Name:";
cin.ignore();
getline(cin,students[count].studentName);
cout<<"\nA-Number:";
cin>>students[count].aNumber;
if(students[count].aNumber == -999)
break;
cout<<"\nOutstanding Balance:";
cin>>students[count].outstandingBalance;
}
cout<<setw(20)<<"A-Number"<<"Name"<<"Balance";
for(int count2 = 29; count2 >= maxStudents-1; count2--)
cout<<setw(20)<<students[count2].aNumber<<students[count2].studentName<<students[count2].outstandingBalance;
system("pause");
return 0;
}
Look up C++ FAQ on iostreams.
Item 15.6 specifically deals with your problem ("Why is my program ignoring my input request after the first iteration?"), but you may find the whole page useful.
HTH,
Put
cin.ignore();
at the end of the loop.
The reason what you're doing doesn't work is that the '>>' operators the
first time through don't extract the trailing '\n', the next getline
sees it, and returns immediately with an empty line.
The simple answer is: don't mix getline and >>. If the input is
line oriented, use getline. If you need to parse data in the line
using >>, use the string read by getline to initialize a
std::istringstream, and use >> on it.
The problem is with mixing cin and getline. Formatted input (with the >> operator) and unformatted input (getline is an example) don't play well together. You should definitely read more about it. Click here for more explanation.
Here is the solution to your problem.
cin.ignore(1024, '\n'); is the key.
for(int count = 0; count < maxStudents-1; count++)
{
...
cout<<"\nOutstanding Balance:";
cin>>students[count].outstandingBalance;
cin.ignore(1024, '\n');
}
If you have a problem with the skipping with getline()
Use it like this std::getline(cin>>ws,a);
Using ws will skip the white space.
I'm trying to do a simple task of reading space separated numbers from console into a vector<int>, but I'm not getting how to do this properly.
This is what I have done till now:
int n = 0;
vector<int> steps;
while(cin>>n)
{
steps.push_back(n);
}
However, this requires the user to press an invalid character (such as a) to break the while loop. I don't want it.
As soon as user enters numbers like 0 2 3 4 5 and presses Enter I want the loop to be broken. I tried using istream_iterator and cin.getline also, but I couldn't get it working.
I don't know how many elements user will enter, hence I'm using vector.
Please suggest the correct way to do this.
Use a getline combined with an istringstream to extract the numbers.
std::string input;
getline(cin, input);
std::istringstream iss(input);
int temp;
while(iss >> temp)
{
yourvector.push_back(temp);
}
To elaborate on jonsca's answer, here is one possibility, assuming that the user faithfully enters valid integers:
string input;
getline(cin, input);
istringstream parser(input);
vector<int> numbers;
numbers.insert(numbers.begin(),
istream_iterator<int>(parser), istream_iterator<int>());
This will correctly read and parse a valid line of integers from cin. Note that this is using the free function getline, which works with std::strings, and not istream::getline, which works with C-style strings.
This code should help you out, it reads a line to a string and then iterates over it getting out all numbers.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string line;
std::getline(std::cin, line);
std::istringstream in(line, std::istringstream::in);
int n;
vector<int> v;
while (in >> n) {
v.push_back(n);
}
return 0;
}
Also, might be helpful to know that you can stimulate an EOF - Press 'ctrl-z' (windows only, unix-like systems use ctrl-d) in the command line, after you have finished with your inputs. Should help you when you're testing little programs like this - without having to type in an invalid character.
Prompt user after each number or take number count in advance and loop accordingly.
Not a great idea but i saw this in many applications.