C++读取文本文件仅获取最后一行,如何读取全部内容并存储到变量
问题根因
- 仅声明了单个
sample结构体变量,每次给Neighbours成员赋值都会覆盖上一次存储的内容,最终只能保留最后一次赋值的结果 - 代码中
j%2==0的筛选逻辑只会保留偶数下标行(首行下标为0),如果需求是读取所有行,该逻辑属于多余逻辑
修正后的实现代码
要存储所有行数据,我们用vector容器存储多个sample实例,代码如下:
#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; struct sample{ string Neighbours; }; int main() { string mytext; vector<sample> allInputs; // 用vector存储所有行的内容 ifstream MyReadFile("/f.txt"); while(getline(MyReadFile, mytext)) { sample temp; temp.Neighbours = mytext; allInputs.push_back(temp); // 每读一行就存入容器 } MyReadFile.close(); // 输出所有存储的内容验证 for (int i = 0; i < allInputs.size(); i++) { cout << allInputs[i].Neighbours << endl; } return 0; }
可选优化:拆分每行字段存储
如果需要把每行的三个字段(目标IP、本地映射IP、端口)分开存储,可以修改结构体和读取逻辑:
// 新增头文件 #include <sstream> struct sample{ string targetIp; string localIp; int port; }; // 读取部分修改为: while(getline(MyReadFile, mytext)) { sample temp; istringstream ss(mytext); ss >> temp.targetIp >> temp.localIp >> temp.port; allInputs.push_back(temp); }
内容的提问来源于stack exchange,提问作者Kranthi Reddy
相关产品推荐
相关产品推荐

