-2

just wanted to ask something about addition of data. So i have this .txt file that i want to read in using c++. that one has no problem. I can read that using fstream. now that .txt file contains a data of...

Number of monitored events
Event-1:Weight-1:Event-2:Weight-2:Event-3:Weight-3:Event-4:Weight-4:
Event-5:Weight-5: ....:

those above information will have 4 pairs each row, but delimeted by a : now my question is . is it possible to add up the values of all the weight? i can't seems to understand how to read only the weight part as it is all separated by the same delimeter.

Paul
  • 1
  • read line into string, `strtok` "-:" the string into array and get 3rd, 7th, 11th and 15th element, convert to int and add them together – Killzone Kid Feb 17 '18 at 07:30
  • `std::getline` allows you to set the delimiter you want. It only defaults to a newline,so you can `std::getline(inFile, outertoken, ':');` and then `std::getline(strstream, innertoken, '-');` on a `std::stringstream` constructed around `outertoken`. – user4581301 Feb 17 '18 at 08:25
  • ahhh yes now i have manage to get the even positions only and i have converted them to double. now my problemen is the adding part. for example i have 3 5 6 7 8 9.7 i cant seem to add them all up. it keep adding +1 individually – Paul Feb 17 '18 at 09:58

1 Answers1

0

It is possible using castings. You can use another delimiter for the weights and separate it using that token and cast it to integer and you just have to do is addition.

If u want to know how to break tokens, here is the link: C++ Reading file Tokens

  • ohhh the .txt file is going to be given by a facilitator and in that file the delimeter used is : – Paul Feb 17 '18 at 06:47
  • is it possible to read only the even positions of the data in the .txt file. for example monitor events event1:weight1:event2:weight2:event3:weight3:event4:weight4 . . means i will only read weight part – Paul Feb 17 '18 at 06:52
  • In this case, use can build a regular expression which gets the number followed by the weight and store it.The regex obj("regular_exp") use a flag using smatch obj1; and search for pattern using regex_search(s,obj1,obj) where s is string to search. – Karan Velhal Feb 17 '18 at 06:54
  • sorry im new in learning this . may i know what do you mean by build a regular expression – Paul Feb 17 '18 at 06:58
  • Regular expression is a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. You can google it and learn, it will help you for sure. If any difficulty faced contact your professor for a hands on practical. The regular expressions are used in compilers for syntax and semantic analysis. Use this concept it in the code and analyze the data. I am not more handy into c++ as i am in Java and python else i could have provided a code for you. Cheers! – Karan Velhal Feb 17 '18 at 07:04
  • All the best buddy! – Karan Velhal Feb 17 '18 at 10:03