create function to retrive data from CSV file

Hello ,
Currently i work on a Qt Application using C++.
I am really new in c++ development.
I uploaded a CSV file .
I want to create a function to browse this csv file, and retrieve some data.

for example :
my Csv file is compound of 25row and 6 column .

I want getting this 25row and only 3 column .

then I will call this function in another class.

I hope my question is clear for you .

thank you


Do you have any code?

All you really need to do is create a string and you can grab a column value from each row by doing:

1
2
ifstream inFile("test.csv");
getline(inFile, stringName, ',') //',' is the delimiter 


This will grab a column entry on the row you're on.

You'll loop through the getline for as much as you need.
If you write a Qt application, then you have all the Qt classes at your disposal.
For example, the QString has member split(). See https://doc.qt.io/qt-5/qstring.html#split

If one would read one whole line at a time as text and then split by delimiter, then one would have that line's fields in a list from which you can store the interesting elements to appropriate container.
thanks for your reply .
this is my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(int i=0;i<ui->tablewidget->rowCount();i++){

    QTableWidgetItem *cell0 = ui->tablewidget->item(i,0);
    QTableWidgetItem *cell7 = ui->tablewidget->item(i,7);
    QTableWidgetItem *cell3 = ui->tablewidget->item(i,3);

    QVariant myData0 = cell0->data(Qt::DisplayRole);
    QVariant myData7 = cell7->data(Qt::DisplayRole);
    QVariant myData3 = cell3 ->data(Qt::DisplayRole);

    if (myData7=="Core_meas"){
        qDebug() << myData0 << myData7  << myData3;

    }

So what I want is to set myData0 , myData7 and myData3 in a table array because i want to get it in another class .

sorry if my question seems stupid :/
Last edited on
In other words, you should update QTableWidgetItems in QTableWidget when you read data from file?
https://doc.qt.io/qt-5/qtablewidgetitem.html#setData

Qt has also its own QFile, which is used differently from C++ Standard Library I/O:
https://doc.qt.io/qt-5/qfile.html#details
Using the standard C++ library and the (header only) boost tokenizer library (caveat: untested)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <iterator>
#include <boost/tokenizer.hpp>
#include <fstream>

template < typename ITERATOR > using value_type = typename std::iterator_traits<ITERATOR>::value_type ;

template < typename ITERATOR > // col numbers start at zero
std::vector< value_type<ITERATOR> > extract_cols_of_interest( ITERATOR begin, ITERATOR end, const std::set<std::size_t>& col_nos )
{
    std::vector< value_type<ITERATOR> > result ;

    for( std::size_t i = 0 ; begin != end ; ++begin )
        if( col_nos.find(i++) != col_nos.end() ) result.push_back(*begin) ;

    if( result.size() == col_nos.size() ) return result ; // got all the cols
    else return {} ; // badly formed line, return an empty vector
}

// col numbers start at zero
std::vector<std::string> extract_cols_of_interest_from_csv( const std::string& str, const std::set<std::size_t>& col_nos )
{
    // https://www.boost.org/doc/libs/1_76_0/libs/tokenizer/doc/escaped_list_separator.htm
    // uses all defaults: separator character is ',' escape character is '\', quote character is '"'
    boost::tokenizer< boost::escaped_list_separator<char> > tokeniser(str) ;
    return extract_cols_of_interest( tokeniser.begin(), tokeniser.end(), col_nos ) ;
}

// col numbers start at zero
std::vector< std::vector<std::string> > extract_cols_of_interest_from_stream( std::istream& stm, const std::set<std::size_t>& col_nos )
{
    std::vector< std::vector<std::string> > result ;

    std::string line ;
    while( std::getline( stm, line ) )
    {
        auto cols = extract_cols_of_interest_from_csv( line, col_nos ) ;
        if( !cols.empty() ) result.push_back( std::move(cols) ) ;
    }

    return result ;
}

int main() // example usage (to extract col numbers 0, 3 and 7 from the lines in a file)
{
    const std::string file_name = "xyz.csv" ;
    const std::set<std::size_t> cols_of_interest { 0, 3, 7 } ; // col numbers start at zero

    if( std::ifstream file{file_name} )
    {
        const auto extracted_data = extract_cols_of_interest_from_stream( file, cols_of_interest ) ;

        for( const auto& row : extracted_data ) // for each row
        {
            // col #0 is in row[0], col #3 is in row[1] and col #7 is in row[2]
            // do something with the extracted col data
        }
    }
}
To extract just one element from a csv file, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

std::string getValue()
{
	static constexpr size_t ROW {25};	// Starts at 1
	static constexpr size_t COL {3};	// Starts at 1
	static constexpr char DELIM {','};

	std::string val;
	std::ifstream ifs("csvfile.txt");

	if (ifs) {
		for (size_t r = 1; std::getline(ifs, val) && r < ROW; ++r);

		if (ifs) {
			std::istringstream iss(val);

			for (size_t c = 1; std::getline(iss, val, DELIM) && c < COL; ++c);
		}
	} else
		std::cout << "Cannot open file\n";

	return {std::find_if_not(val.begin(), val.end(), [](char ch) { return ch == ' '; }), std::find_if_not(val.rbegin(), val.rend(), [](char ch) { return ch == ' '; }).base()};
}

int main()
{
	std::cout << getValue() << '\n';
}


Given csvfile.txt:


hhhhh, i, yy, u, tttttttt, gggggg
r, r, kkkkkkkk, ppppp, wwwww, j
dddddd, hh, eeeeeee, h, vvvvv, hhhhhhhh
sssssss, lll, oooooo, ggggg, nnnnnnn, tttttttt
aaaaaaa, m, dddddd, xxx, ttttttt, mmm
eeeeeee, ffff, xxxx, aaaa, dddddddd, ccccccc
vvvvvv, qq, tttt, cc, n, iiiiii
p, pp, vvvvvvv, zzzzzz, cc, fffffff
kkk, llll, nnnnnn, xxx, mmmmmmm, bbbbb
rrrrrrr, lllllll, vvvvvvv, zzz, kkkk, aaaaaa
ooo, rrr, nnnnnnn, bbbbbbbb, ss, eeeeeee
aaaaaaaa, v, kk, cccccc, e, xxxxxxx
zzzzzzzz, aaaaaaa, mmmmmmm, iiiiiii, hhhhhh, ii
jjjjjjj, w, xxxxxxxx, eeeeeee, mmmmmmm, jjjjjjj
nnnnnn, sssss, k, xx, uuuuu, nnnn
kkkk, ggggg, ffffff, ggg, qq, tttttttt
nnnnn, kkk, nn, ddddddd, cccc, vv
bbbbbbbb, xxxxxxxx, eeeee, x, ssssssss, mmmmmmmm
eee, yyyyyy, bbbbbbb, uuuuuuu, ll, vvv
ee, sssssss, zzz, ddddd, eeeee, r
v, nnnnnn, eeeee, v, mmmmmmm, rrr
qqqqqqq, eeeee, ddddddd, bbbbbbb, qqqqqqq, q
iiii, ffffff, z, kkkkkk, d, ttt
lll, ssssss, xxxxxxx, pp, x, zz
rrrr, uuuuuuu, dddddddd, iiii, kkkkkk, eeeee


displays:


dddddddd

Topic archived. No new replies allowed.