Блог пользователя nosferrati_1941

Автор nosferrati_1941, история, 6 месяцев назад, По-английски

In this problem A : Free Ice Cream, upon taking the string inputs, why is the null string read in the first iteration? Below shows my accepted soln. (the soln I rather proposed in my mind was to run the loop from i=0 to i<n which throws errors.

#include<bits/stdc++.h>
using namespace std;

int main(){
    long long int n,x;
    cin>>n>>x;
    long long int cnt=0, ans=x;
    for(int i=0;i<=n;i++){
        string s;
        getline(cin,s);
        if(i==0) continue;
        auto temp = s.substr(2);
        long long int num = stoi(temp);
        if(s[0]=='+'){
            ans+=num;
        }
        else{
            if(ans>=num){
                ans-=num;
            }
            else{
                cnt++;
            }
        }
    }
    cout<<ans<<" "<<cnt<<endl;
}
  • Проголосовать: нравится
  • +9
  • Проголосовать: не нравится

»
6 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by nosferrati_1941 (previous revision, new revision, compare).

»
6 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

When the integer variables n and x are read, the file cursor is set to the newline after the integer x; the newline itself hasn't been read yet. Since the function getline reads a string until the next newline, regardless if any valid characters have been read, the first call to getline returns an empty string since it reads that newline and immediately stops.

In this problem, it is more advisable to read the character '+' or '-' and the integer $$$d$$$ separately using the following code segment:

char op;
int d;
cin >> op >> d;

Direct reads to types like char or int will never stop until actual content has been read, skipping all prior whitespace, and is a better choice in most cases for competitive programming.