Click here to Skip to main content
15,919,749 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am stuck trying to convert a delimited text file with five columns of data structured like this:

col1 col2 col3 col4 col5
#1   #1    #1   #1   #1
#2   #2    #2   #2   #2
#3   #3    #3   #3   #3

I can print out each line of the text file easily using the code below (which I found on the internet). The problem is that each line is interpreted as a string, and I need each number in each column to be a float variable in an array. Does anyone know how to do this?

What I have tried:

ifstream myfile ("cmb.txt");
  if (myfile.is_open())
    while(getline(myfile, line)) {
      cout << line << endl;
Updated 23-Apr-24 6:53am
PIEBALDconsult 23-Apr-24 12:55pm    
fscanf ?
strtok and atof ?

#include <fstream>
#include <iostream>
#include <array>
#include <vector>
using namespace std;

using Row = array<double, 5>;

int main()
  vector < Row > v;

  ifstream ifs("cmb.txt");

  if (ifs)
    string line;
    getline(ifs, line); // read and discard the header
  for (;;)
    Row row;
    for (auto & d : row)
      ifs >> d; // read all the items of the row
    if ( !ifs) break;
    v.push_back(row); // append the row to the vector

  // print a sample item
  cout << "v[2][2] = " << v[2][2] << "\n";
Share this answer
jeron1 23-Apr-24 13:47pm    
Nice! +5
CPallini 23-Apr-24 13:50pm    
Thank you, man!
Take a look at std::basic_istream<CharT,Traits>::operator>> -[^]
Look at the example code, which shows you how to read a value from a file into a variable. This assumes that your data (#1, #2, #3 etc) are all normally formatted numbers, separated by white space (space, tab, etc), otherwise you'll have to massage your data on read. There's also an assumption here that you know how many rows and columns you have, so can arrange to pre-size (either dynamically using new or a smart pointer, or statically with something like double data[100][100]
If you don't know the rows and columns ahead of time, you might want to consider using a vector of vectors (e.g. vector<vector<double>>. In this case you'd use getline() to read in a line of text from the file, parse out the columns (see std::basic_stringstream -[^] on how you might do that) to construct the row vector, and then push_back() the row vector into the enclosing matrix.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900