I have to make a TXT file with data coming from a CSV.
They are currently ordered in the format 1,3,2,4,7,2,3,1,4,3 . When 1 is the number to repeat and the next number the times to reapeat.
The objective is make the output with this format:
1
1
1
2
2
2
2
7
7
3
4
4
4
I can currently display only the numbers one below the other but not the repeating. Any help will be appreciated. It's my first post here, so if there's anything wrong let me know, thanks!
void lectura(string archivo){
string linea; //string to save the line of numbers
vector <string> numeros; //vector to save the line
ifstream entrada(archivo.c_str()); //open csv to read
ofstream signal( "datos_de_senial.txt", ios::out); //open csv to write
int pos =0;
while(getline(entrada, linea)){ //get the line
istringstream in(linea); //convert to istingstream
string num;
if(pos==0){
while (getline(in, num, ',')){ //get the numbers separated by ","
numeros.push_back(num); //save to vector"numeros"
}
for(unsigned int x = 0; x < numeros.size(); x++) //show one number below the other,here i think the problem is
signal << numeros[x] << '\n';
}
}
signal.close();
}
int main(int argc, char *argv[]) {
void lectura(string archivo);
string csv = "signals.csv";
lectura(csv);
return 0;
}
I drafted an ultra simple solution for you. With that, you can easily see, how to print the values as you wish.
Because of the simplicity of this solution there is no further explanation needed.
#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
#include <regex>
std::regex re(",");
std::string csv{"1,3,2,4,7,2,3,1,4,3"};
int main() {
// Read all data from the file
std::vector<std::string> data(std::sregex_token_iterator(csv.begin(),csv.end(),re,-1), {});
// iterate through data
for (std::vector<std::string>::iterator iter = data.begin(); iter != data.end(); ++iter) {
// Read the value
int value = std::stoi(*iter);
// Point to next value, the repeat count
++iter;
int repeatCount = std::stoi(*iter);
// Now output
for (int i=0; i < repeatCount; ++i)
std::cout << value << "\n";
}
return 0;
}
Of course there are also many other possible solutions . . .