I have a task that I have to do with C++,
And so far I am finding it quite complicated since I am a beginner.
Would someone please be so kind and advise me what functions and arrays or variable to use to achieve this:
There are 2 files together with .cpp file, one called in.txt and other out.txt.
Program needs to open file in.txt and check for all integers that are entered in this file.
Program removes all not-needed symbols and afterwards sorts integers by value (ok this one I will do with bubble swapping method.)
However I am unsure how should I get all integers and take off for example letters from the file.
Here is what program should do:
in.txt
11 23s5 66 19
32
out.txt
should be like this- 5 11 19 23 32 66
So far I just created and string and added all strings from file to my string with append.
Afterwards I copied this string to char array and removed everything that is not "IsDigit" from the array.
But now started the hardest part, since I cannot allocate where are integers and I have black spaces in my array.. and also array is char not integer..
---- I don't need full code, I just wanted to ask ideas what to use to achieve this.
Should I read string / int from file, should I use arrays or vectors??
You could read an integer from the file like this.
1 2 3
std::ifstream fin("in.txt");
int n;
fin >> n;
However, since the file contains non-numeric data, you need to check whether or not the input worked.
1 2 3 4 5 6 7 8 9
if (fin >> n)
{
// do something with the integer n
}
elseif (!fin.eof()) // if we haven't reached the end of the file
{
fin.clear(); // reset error flags
fin.ignore(); // ignore just one character
}
This is one of the very few occasions where checking for end of file is useful.
Put the above code inside a loop to repeat while (fin).
I'd store the integers in a vector, use std::sort to put them in sequence, and then loop through the vector and send them to the output file.
The above should work even if there are negative numbers in the input file. If you are only dealing with alphabetic characters and positive integers, the original idea of reading as a string could work, replace each non-numeric character in the string with a space, and then use a stringstream to extract all the integers from the string.
@Chervil - thank you very much for your input,
can't wait to try this out. :) I will let you know how it goes and post my code If I have any problems.
@TheSmallGuy - if you read my post again, I stated that I don't need my homework done with the code, I am just asking for basic advice how to start properly to be able to achieve this task. I find myself learning this way the most, like, following Chervils advice and ideas.