6 / 6
Nov 2017

While using getline in a c++ code it is taking the first string as the null character probably and thus missing the last string from the input. Probably I am missing out something regarding the use of getline. Any help is appreciated The code with input and output is below:

CODE
#include
#include
using namespace std;

int main() {
short int t,i;
cin>>t;
string a;
while(t–)
{
getline(cin,a);
cout<<"length of string is "<<a.length()<<endl;
for(i=0;i<a.length()/2;i+=2)
{
cout<<a[i];
}
cout<<endl;
}
return 0;
}

INPUT
4
hello
understand
think
programming

OUTPUT
length of string is 0

length of string is 5
h
length of string is 10
udr
length of string is 5
t

  • created

    Nov '17
  • last reply

    Nov '17
  • 5

    replies

  • 1.4k

    views

  • 3

    users

  • 1

    like

  • 1

    link

...
using namespace std;
int main () {
   short int t, i;
   cin >> t;
   string a;
   getline (cin, a);  ///<--- to "eat" '\n' after "4\n"  !! ;-)
   while (t–)
   {
     getline (cin, a);
.....

Please! :wink: Read my [earlier] post little careful! :wink:

TIP

cout << "Find in fragment of your code line added by me, please! ;-) \n"

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 34 26d

Want to read more? Browse other topics in C and C++ or view latest topics.