push_back() problems
push_back() problems
我想将行存储在等文件中
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
希望有帮助,
相关文章:
- Problems with std::cin.fail()
- 推导 std::vector::back() 的返回类型
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- QT GStreamer Windows linker problems
- vector.push_back(vector.back()+1) 是未定义的行为吗?
- Problems with emscripten (WebAssembly)
- 为什么当我从语句检查中删除"+ mod"时,以下程序给出错误的答案。问题链接:https://www.codechef.com/problems/FFC219B
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- Problems with QByteArray::right
- std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误
- vector.back()和vector.end()有什么区别
- 列表大小为 1,但 front() 和 back() 不相等
- glutPassiveMotionFunc problems
- 返回C++中没有 back() 方法的容器的最后一个元素?
- 在非空 std::list 上使用 std::list.back<int>() 时"Segmentation Fault"
- Problems in using ?: as if statement in C++
- MPI Isend and Irecv problems
- 我们可以使用Back() - 值索引在其上执行向量插入
- 当我运行以下代码添加str.front() str.back时,它给了我200个,但为什么
- 链表回推操作中需要'back pointer'