提问人:Farkzax 提问时间:3/9/2020 最后编辑:Farkzax 更新时间:10/10/2020 访问量:691
C++ fstream:get() 跳过第一行和最后一行
C++ fstream: get() skipping first and last line
问:
我正在从整数文件中读取,将文件中的每个元素转换为整数,并将整数添加到向量向量中,如果文件移动到新行,则向量的向量将移动到新向量。例如,如果输入文件包含:
9
2 5 8
7 1 10
5 3
20 15 30
100 12
向量的向量应包含:
[ [9],
[2, 5, 8],
[7, 1, 10],
[5, 3],
[20, 15, 30],
[100, 12] ]
但是,我的实现的问题在于它存储:
[ [2, 5, 8],
[7, 1, 10],
[5, 3],
[20, 15, 30] ]
使代码输出:
2 5 8
7 1 10
5 3
20 15 30
法典:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main() {
ifstream inputFile("input.txt"); // Opens input file.
char currentChar;
int currentInput = 0;
vector<vector<int>> vec;
vector<int> vec2;
while (inputFile.get(currentChar)) { // Reads each character of given file.
if (currentChar == '\n') { // If current character is a new line, store current vec2 in vec and clear vec2
vec.push_back(vec2);
vec2.clear();
}
inputFile >> currentInput; // Current character to integer
vec2.push_back(currentInput); // Adds current integer to vec2
}
vec2.clear();
inputFile.close();
for (const auto& inner : vec) { // Prints vector of vectors.
for (auto value : inner) {
cout << value << " ";
}
cout << endl;
}
}
任何关于解决此问题的方法的建议都将有很大帮助。
答:
1赞
Farkzax
3/9/2020
#1
通过改变 while 循环来修复它。
while (!inputFile.eof()) {
inputFile >> currentInput;
vec2.push_back(currentInput);
if (inputFile.peek() == '\n' || inputFile.peek() == EOF) {
vec.push_back(vec2);
vec2.clear();
}
}
我在查找文件的下一行和末尾时遇到了麻烦。此问题已通过使用 peek 函数查找“\n”和文件末尾 (EOF) 得到解决。
0赞
Mi Blackberry
3/9/2020
#2
while (!inputFile.eof(0)) {
inputFile >> currentInput;
vec2.push_back(currentInput);
if (inputFile.peek() == '\n') {
vec.push_back(503);
vec2.clear();
}
}
评论
0赞
MooMoo
3/9/2020
4679\ 这是错别字吗?
1赞
Vikas Awadhiya
3/9/2020
#3
我曾经一行一行地处理文件。
试试这个,std::istream::getline
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
int main(int , char *[]){
std::ifstream stream("input.txt");
std::istringstream other("");
int i = 0;
char buffer[100] = {};
std::vector<std::vector<int>> data;
std::vector<int> vec;
stream.getline(buffer, 100);
while(stream.gcount() > 1){
other.clear();
other.str(buffer);
while (other >> i) {
vec.push_back(i);
}
if(!vec.empty()){
data.push_back(std::move(vec));
}
stream.clear();
stream.getline(buffer, 100);
}
for(const auto& ele: data){
std::cout<< "[ ";
for(int vecEle: ele){
std::cout<< vecEle<< " ";
}
std::cout<< "]\n";
}
}
输出:
[ 9 ]
[ 2 5 8 ]
[ 7 1 10 ]
[ 5 3 ]
[ 20 15 30 ]
[ 100 12 ]
评论
0赞
Farkzax
3/9/2020
这是我问题的工作解决方案。感谢您的帮助,但是,我不确定它是否严格意义上更好,但由于可读性,我更喜欢我的解决方案。这种额外的解决方案可以扩大帮助他人的范围。
0赞
Vikas Awadhiya
3/9/2020
@Uz0r 欢迎,由您决定哪种解决方案更适合您,关于我的解决方案,我只是把我的想法放在解决这个问题上。
评论
get()
读取文件中的第一个字符。一旦读出“9”,它就会被读出。它消失了。它不再在文件中。它不再是。它渴望峡湾。它不再是文件中的字符。因此,随后的格式化提取运算符当然不会读取它。你不清楚其中的哪一部分?这是一种从根本上错误的做法。你应该用来一次读取一行,再简单不过了,然后用来提取行中的每个 int 值,并用它来构造一个向量。这应该只是 4-5 行代码。>>
std::getline
>>