dimanche 25 octobre 2020

Number of substrings starting and ending with '1'

I'm trying to find the number of substrings that start and end with '1' where input string are numbers like 1111, 10001 etc. Given code does not show correct output but if I replace getline with cin as the input method the code works fine. It also works if I skip input of n and use i<str.length() in for loop. Why does this happen?

#include <iostream>
#include <string>
using namespace std;
    
int main(){
    int n;
    cin>>n;
    string str;
    getline(cin,str);
    int c=0;
    for(int i=0;i<n;i++)
    if(str[i]=='1')
    c++;
    c=c*(c+1)/2;
    cout<<c;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire