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.
8 Respostas
+ 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
+ 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/
+ 4
Use fstrean object
+ 3
Dear I have codes of this topic, which will clear your concepts. Inbox me, I will guide you better and provide you material
+ 2
For converting string to int you should use this syntax atoi
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 ?!)
0
Android Developer👨💻 I have already used it but I have a problem in converting from a string to int
- 1
hi