getline()函数中的问题...... [英] Problems in getline() function...

查看:71
本文介绍了getline()函数中的问题......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算我需要点击按钮在移动设备上写一条消息的次数... getline()函数第一次没有工作,第二次没有工作输入...输出格式应为:

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:

Case #1: 29
Case #2: 41



但我的输出显示:


but my output is showing :

Case #1: 0




Case #2: 29



获得相同的输入:




for the same input:

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

推荐答案

您第一次拨打getline,将使用< CR>数字末尾的字符,因此您的字符串变量将是一个空字符串。您应该调用 getline 来清除输入。您也不应该使用 for loop top获取输入字符串的长度,因为您可以通过 s.length()获取它,或在字符串上使用迭代器。让代码正常工作的最简单方法是修改开头,如下所示:

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:
   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();
...


这篇关于getline()函数中的问题......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆