-2

我想将行存储在文件中,例如

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

成为数组的元素。所以如果我这样做

#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
}

但我收到错误:
无法调用向量 >::pushBack(lineElement)

4

3 回答 3

2

更改lineArr为:

vector<string> lineArr;

你的sscanf也坏了,你不能用std::string. 整个事情应该是:

lineArr.push_back(line);
于 2012-08-28T14:19:33.083 回答
1

好吧,您的向量包含单个chars

vector <char> lineArr;

看起来你正试图推动一个std::string

于 2012-08-28T14:21:04.033 回答
0

除了以前的好答案,请找到一个完整的工作程序:

#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;
 }

哪个将输出,关于您的输入文件:

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

希望能帮助到你,

于 2012-08-28T14:35:00.040 回答