Hey,
what is the best way to handle obtaining int array from file like this:
1,0.2,3,4
2,4,6,8.24
16.2,7.45,2
when numbers can be seperatet by ',' or '.'.
I cant use readline() since i have 2 diff delims.
I assume that your title meant to say "data" and not "date".
Anyway, just reading an integer will stop at the first character that isn't part of an integer, which includes commas and periods. Then you can just read a character to get rid of the delimiter.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
std::ifstream fin("filename");
std::string line;
while (std::getline(fin, line)) {
std::istringstream iss(line);
int n;
while (iss >> n) {
// do something with n ...
std::cout << n << '\n';
char ch;
iss >> ch; // eat the delimiter (whatever it is)
// you can check that it's a ',' or '.' if you want
}
}
}
I think you are misunderstanding what type of file you have. It looks to me like it is a "CSV", comma separated value file, and the "1.0", "16.2" and "7.45" are actually floating point numbers not numbers separated by a period.
Should the period be a delimiter then tpb's example will work. I am also thinking that you could adjust tpb's example to read directly from the file and achieve the same results.
In any case if you are reading these numbers into an "int" reading a floating point number will still work although you will drop the decimal portion and only store the whole number.
I am also thinking that you could adjust tpb's example to read directly from the file and achieve the same results.
It depends on what "results" he wants. I was assuming that it was important to know how many "integers" come from each line.
I also thought it looked like floating point values and would've assumed that was the case but for the fact that there are not the same number of values on each line (unless he's simply missing a value from the last line). Still, it's hard to imagine that the period is really a delimiter.
#include <iostream>
#include <fstream>
#include <sstream>
#include <chrono>
#include <thread>
constexpr size_t MAXSIZE{ 15 };
int main()
{
int numbers[MAXSIZE]{}, num{};
size_t count{};
std::string line, sNum;
char ch{};
std::ifstream inFile("Input File.txt");
if (!inFile)
{
std::cout << "\n File \"input File.txt\" did not open" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5)); // Requires header files "chrono" and "thread"
exit(1);
}
while (std::getline(inFile, line))
{
std::istringstream iss(line);
while (std::getline(iss, sNum, ','))
{
numbers[count] = std::stoi(sNum);
count++;
}
}
inFile.close();
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue";
std::cin.get();
return 0;
}