This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
main function
int main(){
long long int T;
string s;
cin >> T;
while(T--){
getline(cin, s);
cout << s << endl;
}
}
while loop skipping input on first iteration
only printing blank lines
I want pass string as input on every iteration but on first iteration while loop is skipping input line.
cin >> T reads to the end of the number and not to the end of the line.
So with the first getline(cin, s); you read the rest of the line after the number.
You can call cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); right after the cin >> T; to ignore everything that is left in that line.
You need to use std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); because it ignores the rest of the line up until "\n" or EOF.
Now the std::numeric_limits<std::streamsize>::max() is basically telling cin that there is no limit to the number of characters to ignore.
Also, it might make more sense to use a for loop.
For example:
#include <iostream>
#include <string>
int main()
{
long long int T;
std::cin >> T;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (int i = 0; i < T; i--)
{
std::string s;
std::getline (std::cin, s);
std::cout << s << std::endl;
}
return 0;
}
Also check out why you shouldn't use using namespace std;
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 1 year ago.
I have to read the test cast as follows.
3
ababa
abc
babac
c++ code to read the above input.
int main() {
int t;
cin>>t;
while(t--){
string s;
getline(cin,s);
cin.clear();
cout<<s<<endl;
}
return 0;
}
but the output I'm getting is
ababa
abc
can you help me how to read the last line?
When you do
cin >> t;
the Enter key you used to end that input is left in the input buffer as a newline. This newline will be read by the first call to getline as an "empty" line.
A simple solution is to ignore the remaining of the input after getting the input for t:
cin >> t;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I also recommend that you use the status of the stream as part of the loop condition:
string s;
while (t-- && getline(cin, s))
{
cout << s << '\n';
}
This way you won't be attempting to read beyond the end of the input.
Why not simply use cin >> s; unless there are multiple words in a string
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
cout << s << endl;
}
return 0;
}
To read the last line, you can use cin>>s; to read the string instead of
getline(cin,s);
cin.clear();```
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 3 years ago.
I have a C++ program. I want to get a number from the user (t) and force the user to enter line t times but the program's execution terminates after 1 iteration. This is the code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int t;
cin >> t;
for (int i=0; i< t; i++) {
getline(cin, str);
cout << str;
}
return 0;
}
Can anyone explain me why this happening and how to solve it?
Thank you my friends.
The newline character is still in the buffer when you do cin >> t so the next line you read will be blank. When you mix formatted input (>>) and unformatted (std::getline) you often get in situations like this and you need to take measures when switching to unformatted input. Example remedy:
#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main() {
string str;
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // skip the rest of the line
for(int i = 0; i < t; i++) {
if(getline(cin, str)) // check that the getline actually succeeded
cout << str << '\n';
else
break;
}
return 0;
}
When you enter your first character (the times to repeat), a character is left in the cin buffer - newlines are not consumed by cin >>. As a result, getline(cin, str) reads this character and takes it as the first input, which then empties the buffer out and lets you enter the others.
You can clear the buffer with std::cin.ignore(1); to remove that trailing character - this lets your code run as anticipated. Why not just use cin >> str, though? That solves the problem and avoids a call to getline.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int t;
cin >> t;
//clear one character out of buffer
cin.ignore(1);
//note that 1 is used for demonstration purposes
//in development code, INT_MAX, numeric_limits<streamsize>::max(),
//or some other large number would be best, followed
//by std::cin.clear()
for (int i=0; i< t; i++) {
cout << "input: ";
//you could use cin >> str; instead of getline(cin, str);
getline(cin, str);
cout << "got: " << str << std::endl;
}
return 0;
}
Demo
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 8 years ago.
The getline(cin, s1) function is not prompting me to input a string. it appears as if it is being skipped over even when the if condition is being met. any help? code is below. the problem is in the first if statement.
//Exercise 3.2
#include "stdafx.h"
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
char a1;
cout << "Read line (L) or word (W)?:";
cin >> a1;
if (a1 == 'l'){
string s1;
getline(cin, s1);
cout << s1 << endl;
}
else{
string s1;
while (cin >> s1){
cout << s1 << endl;
}
}
system("pause");
return 0;
}
When you do:
cin >> some_char_variable;
it reads the char and leaves the input stream pointer pointing at the next character, which is invariably the newline you entered.
If you then do a getline(), it will get the line, which is delineated by that newline in the input stream that you left there.
This is the same problem as when you mix getchar() and fgets() in C, the combination of which generally always confuses newcomers.
I tend to avoid mixing the two styles, such as by using getline() everywhere, such as with:
string choice;
getline(cin, choice);
if (choice[0] == 'l') ...
But, if you must mix them, you can clear out the line before trying to accept more data, with something like:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
I am using getline and ignore but something is not working properly,
Below is the sample code which am not able to understand how it is working.
int main()
{
string str;
int t,length;
cin>>t; // t is the number of test cases
while(t--!=0)
{
cin.ignore();
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
Sample output:
2
hey hi
length 6
hey hi
length 5
Why is the length decreasing? Is this because of getline and ignore function? Any help would be appreciated.
The reason it is giving a different length is becaus your ignore() function ignores only one character. The first time round it ignores the return key you pressed after entering the number. But std::getline() deletes the return character for you. So the second time round ignore() deletes the first letter of your string making it "eh hi".
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// first removed RETURN character after removes first letter
cin.ignore();
getline(cin, str);
length = str.size();
cout << "length = " << length;
}
}
Try using this instead:
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// cin.ignore(); // dont do this here please
// cin >> ws skips all whitespace characters
// including the return character
getline(cin >> ws, str);
length = str.size();
cout << " length = " << length;
}
}
Alternatively (maybe better) you can move the ignore() function out of the loop to where t is really needed:
#include <limits>
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
// ignore as many characters as necessary including the return
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(t-- != 0)
{
// cin.ignore(); // not here
getline(cin, str);
length = str.size();
cout << " length = " << length;
}
}
The cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); looks complicated but it is the only way to guarantee that any spurious characters (like spaces) are removed. You can probably get away with just cin.ignore() for the exercise if you want.
Read up on std::istream::ignore()
cin.ignore() defaults to ignoring one character.
If you output your string each time, you'll see that in later cases the string is equal to "ey hi". The h is being dropped.
The value of the string held by cin drops its first character before being passed to getline.
Since you're using getline, you can simply remove the cin.ignore() from your loop and your program should work as intended.
However, you should also change your cin>>t; line. In this case, the ignore() is dropping the line return after the input value 2. A stringstream here allows for a getline(...) function, or alternatively you can use cin.ignore(str.max_size(), '\n');.
In the case of the stringstream, your code would become:
#include <sstream> // stringstream
#include <string> // std::string
#include <iostream> // cin
int main()
{
string str;
int t,length;
getline(cin, str);
std::stringstream stream;
stream << str;
if (!(stream >> t)) {
// Couldn't process to int
}
// cin>>t; // t is the number of test cases
// No longer need this line.
while(t--!=0)
{
// cin.ignore(); Drop this too
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
If you are not interested in whitespace,
then use getline(cin >> ws, str)
This question already has answers here:
cin>> not work with getline()
(2 answers)
Closed 8 years ago.
Compiler version is 4.2 g++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a[10];
int i;
int N;
cin>>N;
for (i=0; i<N; i++)
{
getline(cin,a[i]);
}
return 0;
}
When I input 2 . It asks for input once. When 3 then 2 times . And so on. Please solve. THANKS.
The first getline call reads end-of-line character that is still sitting in the input buffer after the N is read.
Consider this as the following input:
3 First string
Second string
Third string
In your case, the first string is just empty.
If you want to ignore whitespaces after the N, write something like
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
(will skip to the end of line), or
cin >> N >> std::ws;
(will skip all whitespace characters, end of line included).
After inputting a value for N, there is a \n (end of line) character left in the buffer. The first getline sees that as the first character, and returns an empty string. Simply do this:
string a[10];
int i;
int N;
cin>>N;
cin.ignore(INT_MAX);//flush buffer
for (i=0; i<N; i++)
{
getline(cin,a[i]);
}
This will flush the buffer before the for() loop.
the problem is that when press enter or space it is taking that also as input
#include <iostream>
include <string>
using namespace std;
main()
{
string a[10];
int i;
int N;
cin >> N >> std::ws;
for (i=0; i<N; i++)
{
getline(cin,a[i]);
}
return 0;
}