getline C++ not getting result that is required [duplicate] - c++

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;
}

Related

why loop is skipping input in first iteration? [duplicate]

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;

I want to count the upper-case characters in a string. Why is my code is giving wrong output?

I am working on a programming exercise, "Count of camel case characters" using C++. The goal of the exercise is to count the number of upper-case letters in a given string (what the exercise calls "camel case").
So given the following two inputs:
ckjkUUYII
HKJT
I would expect to get the following counts respectively:
5
4
Based on the code I've include below, however, I am instead getting:
0
5
This is clearly incorrect, but I've having difficulty isolating the problem in my code. How can I reason through this problem, or debug my error?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int t;cin>>t;
while(t--)
{
int res=0;
string str;
getline(cin,str);
int len= str.length();
for(int i=0;i<len;i++)
{
int c=str[i];
if(isupper(c))
res=res+1;
}
cout<<res<<endl;
}
//return 0;
}
After entering integer value as t, in input buffer newline character is left. So first call of getline gives you empty string as a result. You have to do:
int t;
cin >> t;
cin.ignore();
while (t--) {
...
}
to consume newline character, then both calls of getline will return entered strings properly.
The main problem is that you are trying to convert a character into an integer in line 15. An integer can't be either uppercase or lowercase. hence it gives the wrong answer. Simply check isupper(s[i]) as it would give the correct answer.
Consider my code,
#include <bits/stdc++.h>
using namespace std ;
int main() {
int t ; cin >> t ;
while(t--) {
string s ; cin >> s ;
int cnt = 0 , ln = s.size() ;
for(int i = 0 ; i < ln ; i ++) {
if(isupper(s[i])) cnt ++ ;
}
cout << cnt << endl ;
}
return 0;
}

How to get string input n times? [duplicate]

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

terminate while loop using character

I need help with the following snippet:
Using string in the following loop terminates:
int main() {
string in;
while(1){
cin >> in;
if (in == "|")
break;
}
But using int in the following loop does not terminates:
int main() {
int in;
while(1){
cin >> in;
if (in == '|')
break;
else
cout<< in << "\n";
}
I want to terminate the last shown snippet. Is it possible to do using int in.
I've seen the post C++ Terminate loop using a char input to int but no solution.
While characters are represented in the computer as small integers, an int is not the same as a char. Not in C++.
When you read into an int variable the >> operator tries to parse the input as an integer, as a number and not as a character.
If you want to read a character then read a character:
char in;
std::cin >> in;
If you try to read an integer, and the input is not a number, then the input operator will fail. See e.g. this very simple example.
This is the approach I used
I needed to input integers to a vector as input using while loop indefinitely and terminate it using a character.
This approach takes the input as character and then convert this char into integer.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
char in;
std::vector<int> vec;
while(1){
cin>>in;
if(in == '|'){
break;
}
vec.push_back(in - '0');
}
for(int j=0; j<vec.size(); j++){
cout<<vec[j];}
return 0;
}

String not getting stored in vector?

#include <iostream>
#include <vector>
using namespace std;
int main()
{
string n, m;
vector <string> dingdong;
cin >> n;
dingdong.push_back(n);
cin >> m;
dingdong.push_back(m);
for (int i = 0; i <2; i ++) {
cout << dingdong[i];
}
return 0;
}
When I run the program and I input "hay sombody there" and hit enter. The program prints "haysombody." So I figured if I increase 'i' to 3 the program will print "haysombodythere" but no, main just crashes. why is this happening and how do I make it so that the entire strings (including the spaces) get stored?
"why is this happening and how do I make it so that the entire strings (including the spaces) get stored?"
To get more than a single word from the input you should use
std::getline(cin,n);
instead of
std::cin >> n;
White spaces are used as delimiters by default, so each call of std::istream's operator>> will just store the text read up to the next white space character.
See a fully fixed version of your program here please.
Also if you really want to read into the vector word by word, you use a loop doing so
string word;
vector <string> dingdong;
while(cin >> word) {
if(word.empty) {
break;
}
dingdong.push_back(word);
}
and print out like
for (int i = 0; i < dingdong.size(); ++i) {
cout << dingdong[i];
}