我想将行存储在
等文件中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
}
但我收到错误:
无法调用vector&gt; :: pushBack(lineElement)
答案 0 :(得分:2)
将lineArr
更改为:
vector<string> lineArr;
您的sscanf
也被破坏了,您无法将其与std::string
一起使用。整个事情应该是:
lineArr.push_back(line);
答案 1 :(得分:1)
你的矢量包含单char
个
vector <char> lineArr;
看起来你正试图推动std::string
?
答案 2 :(得分: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
希望它有所帮助,