problemas de push_back()

I would like to store lines in a file such as

15 1 0 0 0 0
33 1 0 0 0 0
29 1 0 0 0 0
18 1 0 0 0 0
25 1 0 0 0 0

to become elements of an array. So if I do

#include <stdio.h>
#include <vector>
using namespace std

char* file = "somefile.txt"
FILE *fb_r = fopen(file,"r");
char line[100];
vector <char> lineArr;
string lineElement;
while(fgets(line,256,fb_r){
  sscanf(line, "%s", &lineElement);
  lineArr.push_back(lineElement);  //problem arises here
}

pero me sale el error:
Can't call vector >::pushBack(lineElement)

preguntado el 28 de agosto de 12 a las 15:08

has considerado usar iostream y getline? -

3 Respuestas

Cambiar lineArr a:

vector<string> lineArr;

Y tu sscanf is broken too, you can't use it with a std::string. The whole thing should probably be:

lineArr.push_back(line);

Respondido 28 ago 12, 15:08

Well your vector contains single chars

vector <char> lineArr;

and it looks like you are trying to push an std::string?

Respondido 28 ago 12, 15:08

In addition to the previous good answers, please find a fully working program :

#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;

int main() {
    const char* file = "somefile.txt";
    FILE *fb_r = fopen(file,"r");
    char line[100];
    vector<string> lineArr;
    string lineElement;
    while(fgets(line,256,fb_r)) {
      lineElement = line;
      lineArr.push_back(lineElement.substr(0, lineElement.size() -1)); // We here remove the carriage return from the input file which you probably do not want
    }

    for(vector<string>::const_iterator lineIter = lineArr.begin(); lineIter != lineArr.end(); lineIter++) {
       cout << *lineIter << std::endl;
    }

    return 0;
 }

Which will output, regarding to your input file :

15 1 0 0 0 0
33 1 0 0 0 0
29 1 0 0 0 0
18 1 0 0 0 0
25 1 0 0 0 0

Espero eso ayude,

Respondido 28 ago 12, 15:08

error says "operator< not defined for vector<string,allocator<string> >::iterator algo.h:453" - fclopez

Escribiste lineIter < lineArr.end() en lugar de lineIter != lineArr.end(), I think it's the cause of your error. - Y__

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.