0

I have input of the following format:

1 2 1 5 6
1 4 1 4
3 4

For each line, I need to print the sum of all integers in that line. I am thinking of taking input as a string, splitting it by space character and then converting it to its respective integral value. Is there a simpler way to read integer input in array till newline using scanf?

Krash
  • 2,085
  • 3
  • 13
  • 36
  • why do you use `scanf` in c++? – bolov Oct 05 '17 at 17:36
  • Because it is faster than cout and I was practising writing code for different input types in competitive coding using c++ – Krash Oct 05 '17 at 17:37
  • 3
    that is a load of BS. Even if, and I emphasize, **even if** scanf is faster than c++ stream, the algorithm and the data structures chosen affect the performance by order of magnitudes more than choosing scanf vs stream or viceversa. – bolov Oct 05 '17 at 17:40
  • 1
    please show your code, its hard to make it simpler without seeing what to make simpler – 463035818_is_not_an_ai Oct 05 '17 at 17:40
  • You can read line and then strtol or `sscanf(buf+pos,"%d%n", &num,&pos)` - both give feedback where the scan stopped and allows to continue from this position – Artemy Vysotsky Oct 05 '17 at 17:41
  • @bolov I am trying to follow Steve Halim's book on competitive programming. In the first chapter itself, he advices to use scanf/printf over cin/cout. I am not a c++ expert so all I am doing is follow his advice. – Krash Oct 05 '17 at 17:51
  • @Krash I see. Please answer me this: you can consult your book, or any source that teaches competitive programming: which is faster in C++: `a / 8` or `a >> 3` where `a` is of type `unsigned` – bolov Oct 05 '17 at 18:03
  • @bolov a >> 3 should be faster, because it performs the same operation by shifting bits which I feel should be faster. – Krash Oct 05 '17 at 18:05
  • @bolov but for such a small value of divisor , probably doesnt matter. a/8 will be faster. – Krash Oct 05 '17 at 18:06
  • 2
    @Krash :) first, thank you for playing my game. You are wrong: the correct answer is: any decent compiler will optimize both of them to the same assembly code see https://godbolt.org/g/3VpCH1 – bolov Oct 05 '17 at 18:07
  • @bolov thank you so much for telling me this. This was awesome :D – Krash Oct 05 '17 at 18:09
  • 2
    my point: usually competitive programming - if it's learned before or as you learn *normal* programming - teaches you some very bad habits (like using global variables, using **smart tricks** and teaching you false assumptions: like bit tricks are faster than regular operations, or like using scanf instead of cin. – bolov Oct 05 '17 at 18:10
  • 2
    learning to solve such competitive tasks is great. Using a programming style like I've seen usually being used in such competitions is bad. – bolov Oct 05 '17 at 18:11

0 Answers0