dush1729's blog

By dush1729, history, 9 years ago, In English

I am trying to solve Niceness of the string but i am getting WA because i think i am unable to process blank lines. For blank lines output will be zero. I am using scanf(" %[^\n]s",a) which will ignore blank lines.

My code

  • Vote: I like it
  • -1
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

std::getline()

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Thank you! getline will behave weirdly if we don't ignore \n. So i came across this. Putting cin.ignore() after scanf("%d",&T) and using getline() gave AC.

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it +9 Vote: I do not like it

      There is no weirdness in getline:

      size_t n;
      cin >> n;
      string s;
      getline(cin, s); // read pointer is just before the end of line, so the empty line is returned after number reading
      for (size_t i = 0; i < n; i++)
      {
          getline(cin, s); // works, as expected
      }
      
      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it +1 Vote: I do not like it

        Got it. By adding extra getline before taking string as input we can ignore \n.

»
9 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Replacing scanf("%s",a) with gets(a) may help. But remember to getchar() after scanf("%d",&T) to skip the '\n' in the first line.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Looks like getchar works a bit faster than cin.ignore(). Thanks!

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    If you want to skip '\n', you can write: scanf("%d\n",&T). But this works with bugs when you debug your program (if you are not reading from the file).

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

scanf is for queers