push_back() problems

push_back() problems

本文关键字:problems back push      更新时间:2023-10-16

我想将行存储在等文件中

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>::pushBack(lineElement)

lineArr更改为:

vector<string> lineArr;

你的sscanf也坏了,你不能和std::string一起使用。整个事情可能应该是:

lineArr.push_back(line);

您的矢量包含单个char s

vector <char> lineArr;

看起来你正试图推出std::string

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

#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

希望有帮助,