0

In this code ,getline is not working for i =1 .but for i = 0 it is working completely fine. What I should do to repeatedly work with the getline function.This code takes a number and checks its divisibility."numb" is taken to store the number.for i = 0 all the calcultions are just fine but when it goes for the 2nd turn ,don't know what happens but cin.getline doesn't work.

#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#define MAX 1050 
using namespace std ;

int call_div (char *num ,long div)
{
    int len =strlen (num) ;
    int now ;
    long extra ;
    for (now = 0,extra=0; now < len; now += 1)
    {
        extra = extra *10 + (num [now] -'0') ;
        extra = extra %div ;
    }
    return extra ;
}

int main (int argc, char const* argv[])
{       
    int testcase,numbers ,flag =0;
    char numb[MAX] ;
    cin >> testcase ;
    getchar() ;


    for (int i = 0; i < testcase; i += 1)
    {
        cout << i << endl ;

        int div[14] ; 
        cin.getline(numb) ; // i= 0 ,it works fine ,i=1 ,it doesn't work
        cin >> numbers ;

        for (int j = 0; j < numbers; j += 1)
        {
            cin >> div[j] ;
        }
        for (int k = 0; k < numbers; k += 1)
        {

            //   cout << div[k]<< ' '   << call_div (numb,div[k]) << endl ;
            if (call_div (numb,div[k])==0)
            {
                flag = 1 ;
            }
            else {
                flag = 0 ;
                break;
            } 
        }
        if (flag==0 )
        {
            cout << "simple"<< endl  ;
        }
        else
            cout << "wonderful" << endl  ;

    }       
    return 0;
} 
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
aroup
  • 315
  • 3
  • 13
  • 1
    1. Use `std::getline`. 2. http://stackoverflow.com/search?q=%5Bc%2B%2B%5D%20getline%20skipping – chris May 20 '13 at 20:43
  • Can you post the output you currently obtain and what you would expect? (and your inputs) – Marc Claesen May 20 '13 at 20:45
  • 1
    `char numb[MAX];` followed by an unchecked `getline(cin,numb);` is a buffer overflow waiting to happen. It would be better to use `std::string`s. – Marc Claesen May 20 '13 at 21:30

1 Answers1

1

I think Your input may look like

something
3 1 2 3
some other thing
4 1 2 3 4

First time You read "something" with getline(). Then your algorithm reads the 3 as numbers, and then the three number followed by that one. And here reading stops. Next time You call getline(), it will continue reading until it reaches the first '\n' character. So it will not read "some other thing" when You want it.

Now I can not try it, but I think it will work fine with an extra "dumb" getline() after the loop that fills the div array.