Click here to Skip to main content
15,919,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i was tried to count how many times i need click buttons to write a message in a mobile...getline() function is not working for the first time it takes nothing and second time it takes input...the output format should be:
C#
Case #1: 29
Case #2: 41

but my output is showing :
C#
Case #1: 0

C#
Case #2: 29

for the same input:

HTML
2
welcome to ulab
good luck and have fu



my code:

What I have tried:

#include <iostream>
#include
using namespace std;

int main()
{
   int n;
   while(cin>>n)
   {
       for(int j=1;j<=n;j++)
       {
           string s;
           getline(cin,s);
           int len=0,count=0;
           for(int i=0;s[i]!='\0';i++)
            len++;
           for(int i=0;i<len;i++)>
           {
               //cout<<s[i]<<" ";
               if(s[i]=='a'||s[i]=='d'||s[i]=='g'||s[i]=='j'||s[i]=='m'||s[i]=='p'||s[i]=='t'||s[i]=='w'||s[i]==' ')
                count++;
               else if(s[i]=='b'||s[i]=='e'||s[i]=='h'||s[i]=='k'||s[i]=='n'||s[i]=='q'||s[i]=='u'||s[i]=='x')
                count+=2;
                else if(s[i]=='c'||s[i]=='f'||s[i]=='i'||s[i]=='l'||s[i]=='o'||s[i]=='r'||s[i]=='v'||s[i]=='y')
                    count+=3;
                else if(s[i]=='z'||s[i]=='s')
                    count+=4;


           }
           cout<<"Case #"<<j<<": "<<count<<endl;
       }
   }



    //cout << "Hello world!" << endl;
    return 0;
}
Posted
Updated 29-Apr-16 5:06am
v2

1 solution

Your first call to getline, will be consuming the <CR> character at the end of your number, so your string variable will be an empty string. You should call getline to clear the input. You also should not use that for loop top get the length of the input string, since you can either get it by s.length(), or use an iterator on the string. The simplest way to get your code working would be to modify the beginning as follows:
C++
   string s;
   while(cin>>n)
   {
       getline(cin,s); // consume the CR character
       for(int j = 1; j <= n; j++)
       {
           getline(cin, s);
           int count = 0;
           int len=s.length();
...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900