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).
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 6 years ago.
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
getline(cin,s);
cout<<s.at(0);
}
return 0;
}
I tried to run this code but it says out_of_range error. This code is not even taking in the string input.
You are mixing line-based input with non-line-based input.
int main()
{
int t;
cin>>t;
When the user enters "123" and then presses the enter key, the "123" part of the input is parsed and ends up as the number 123 in t, but the linebreak resulting from the enter key will remain in the input buffer.
That's non-line-based input.
while(t--) {
string s;
getline(cin,s);
The std::getline function reads everything until a linebreak is encountered. The linebreak from above is still there, so a linebreak is encountered immediately and s remains empty.
That's line-based input.
std::getline also consumes the linebreak it has encountered, but this doesn't help you much anymore:
cout<<s.at(0);
s has size 0 and at(0) tries to access the 1st element. at is required to throw std::out_of_range_error when you try to access a non-existing element.
A good solution would be to switch exclusively to line-based input on the top input layer. Read everything as lines and parse the individual lines as required. Use std::stoi to convert a string to an integer number.
Here is an example:
#include <iostream>
#include <string>
int main()
{
std::string input;
std::getline(std::cin, input);
int t = std::stoi(input);
while(t--)
{
std::string s;
getline(std::cin, s);
std::cout << s.at(0);
}
}
Note that you should consider adding more error handling to your code. What happens when the user enters a negative number?
You can use cin.sync() function to clear extra input buffer.
The code like this:
int main()
{
int t;
cin >> t;
cin.sync(); // add this line
while(t--)
{
string s;
getline(cin, s);
cout<<s.at(0);
}
return 0;
}
The original code to make the string that is empty and you're trying to access the first element. So it says out_of_range error.
This question already has answers here:
Using getline(cin, s) after cin [duplicate]
(13 answers)
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 6 years ago.
#include<iostream>
#include<cstring>
using namespace std;
int main() {
int t;
cin >> t;
string s;
getline(cin, s);
cout << s;
return 0;
}
As soon as I press the enter key after giving input for t, the program terminates as string takes the newline character as input. What can I do? I cannot output something between these two inputs and an enter after t is mandatory.
The Enter key you press to end the input for t is added to the input buffer. So the first input in the buffer seen by getline is the Enter key and it thinks you have given an empty line.
Use the ignore function to skip past the newline:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You can also use two std::getline calls, and use e.g. std::stoi to convert the input an int. Or put in an std::istringstream and extract using the normal >> operator.
You may use getline(cin, s) twice. Fist will ignore rest of first line and the second will actually read what you need or better use cin.ignore() with appropriate arguments
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 :)
This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 8 years ago.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main (void)
{
int c;
cout<<"enter number of test cases\n";
cin>>c;
while (c!=0)
{
string s;
int t;
cout<<"enter number of strings to be entered\n";
cin>>t;
map <string,int> a;
map <string,int>::iterator it;
while ( t!= 0 )
{
getline(cin,s);
it = a.find(s);
if ( it == a.end() )
{
a.insert(pair<string,int>(s,1));
cout<<"New inserted\n";
}
else
{
a[s]++;
cout<<"Value incremented\n";
}
t--;
}
it = a.begin();
cout<<"Value will print\n";
while ( it != a.end() )
{
cout<<it->first<<" "<<it->second<<"\n";
it++;
}
c--;
}
return 0;
}
So, I made this code which first asks for test cases, and then asks for number of strings and then sorts the strings and outputs their frequency.
Now, in this code, as soon as I hit enter after entering the number of strings, the message New Inserted is displayed, meaning that the new line is being put as a string in the map. Why is that happening?
Thanks!
PS: I tried putting fflush(stdin) before getline but it doesnt help either.
scanf reads the number from the input, and leaves a newline character behind. That newline is interpreted by the next getline, and you get an empty line at first.
Fix 1:
read the newline with scanf:
instead of reading the number only:
scanf("%d", &t);
use the following which swallows the newline as well:
scanf("%d\n", &t);
Anyway, it is a bad idea to mix stdio with iostream but you'd get a similar same result if you would use
cin >> t;
Fix 2 (works with streams as well): Ignore the first line read by getline
Fix 3
Use getline to get the numbers into strings and parse them:
getline(cin, s);
istringstream ( s ) >> t;
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.