Why is this not reading as a sting?

Hi all,

It's been a while since I've programmed in C++ but the below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ifstream fin("SMX_Test.csv");
assert(fin);

vector< vector<string> > SM_Invoice;
vector< vector<string> > FG_Report;
string temp = "";
unsigned int x = 0,
			 y = 0;

while( !fin.eof() && (getline(fin, temp))) {
	if(x == 13) {
		x = 0;
		SM_Invoice.push_back(vector<string>());
	}
	SM_Invoice[x][y].push_back(temp);
}

is giving the error 'std::string not convertible to char' on line 15 - why?

Doesn't getline() return a string?
Last edited on
SM_Invoice is a vector<vector<string>>.
SM_Invoice[x][y] is a string.

You are trying to call push_back on a string, and not a vector of strings.

I'm not exactly sure what you're doing but, perhaps you want
SM_Invoice[x].push_back(temp);
Might be easier to create a struct for the data and use simple vector.
However if you have to use nested vectors consider reading them like this:
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
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdio>

using namespace std;

int main()
{
  ifstream fin("SMX_Test.csv");
  if (!fin)
  {
    perror (nullptr);
    return errno;
  }
  vector<vector<string>> SM_Invoice;
  string line;
  while (getline(fin, line)) // for each line in input
  {
    // create tempory vector to store the items
    vector<string> items; 
    // read all data with the stringstream and add to temp vector
    istringstream iss(line);
    string tmp;
    while(iss >> tmp) // extract data and store in items
      items.push_back(tmp);

    SM_Invoice.push_back(items); // finally add items to invoice
  }
  // just to test if we read all data correctly

  for (const auto& v: SM_Invoice)
  {
    for (const auto& s: v)
      cout << s << "\t";

    cout << "\n";
  }
}

Tested with input file:
Anna 2 Hammer
Lisa 3 Knifes
Debbie 5 Spoons

Output:
Anna    2       Hammer
Lisa    3       Knifes
Debbie  5       Spoons

Last edited on
Topic archived. No new replies allowed.