0

count numbers in c++

how can i write a program that counts the amount of integers numbers and amount of double numbers in a .txt file.

18th May 2019, 8:37 AM
Manar Ksm
Manar Ksm - avatar
8 odpowiedzi
+ 13
Manar Ksm Regarding the part about catching cast exceptions, you might want to use try-catch blocks instead of if else. If you look at the std::stoi documentation, you can see that it throws std::invalid_argument, so we can catch that. EDIT: After some testing, it does not seem like std::stoi throws exceptions on floats and double. :< This means that we have to do it ourselves using std::strtol. Please take a look at the second example below. An example with exceptions using std::any: https://code.sololearn.com/cEDXLk7N1O7d/?ref=app std::strtol exception handling: https://code.sololearn.com/cJO4NRAG6kHS/?ref=app
19th May 2019, 2:00 AM
Hatsy Rei
Hatsy Rei - avatar
+ 8
You can use ifstream, the >> operator allows you to read a single word (i.e. a string of characters without whitespaces) from a file. You can then attempt to convert the string to integer, and handle the exceptions (if doubles are found) accordingly. In the process, increment counters which keep track of both integers and doubles. http://www.cplusplus.com/reference/string/stoi/
18th May 2019, 9:56 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Use fstrean object
18th May 2019, 10:38 AM
Muhammad Rashid
Muhammad Rashid - avatar
+ 3
Dear I have codes of this topic, which will clear your concepts. Inbox me, I will guide you better and provide you material
18th May 2019, 10:44 AM
Muhammad Rashid
Muhammad Rashid - avatar
+ 2
For converting string to int you should use this syntax atoi
18th May 2019, 10:51 AM
Muhammad Rashid
Muhammad Rashid - avatar
0
in.open("input.txt"); out.open("output.txt"); string line; while (getline(in, line)) { for (int z = 0; z <line.size(); z++) int num = std::stoi(line); if (num % 10 = 0) { IntegerNum++; } else DoubleNUM++ (am i wrong in converting from a string to int ?!)
18th May 2019, 10:27 AM
Manar Ksm
Manar Ksm - avatar
0
Android Developer👨‍💻 I have already used it but I have a problem in converting from a string to int
18th May 2019, 10:43 AM
Manar Ksm
Manar Ksm - avatar
- 1
hi
25th Dec 2020, 10:39 AM
Mahamad Bitweny
Mahamad Bitweny - avatar