You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用ifstream读取文本文件运行无输出,请求排查错误

问题排查及修复方案

核心问题

  • 多余的奇偶行过滤逻辑:代码中if (j % 2 == 0)的判断只会处理序号为偶数的行(j从0计数,对应文件第1、3、5等行),不符合按顺序读取前4行配置的需求。同时首次进入逻辑块时r初始值为0,四个输出判断的r匹配条件均不满足,后续r每次累加4后永远无法触发输出逻辑。
  • 未校验文件打开状态:如果给定的文件路径错误、权限不足导致文件打开失败,getline会直接返回失败,循环不执行,自然无任何输出。
  • 输入流输出逻辑错误:(istringstream(mytext) >> input.port)返回的是输入流对象本身,直接输出只会打印流的状态值(正常为1,错误为0),不会输出读取到的数值。
  • 缓冲区长度不足:char myIP[10]最大只能存储9个有效字符,标准IPv4地址最长为15个字符(如192.168.255.255),会引发缓冲区溢出风险。

修复后代码

#include<iostream>
#include<fstream>
#include<string.h>
#include<sstream>
using namespace std;

struct sourceInfo{
    char myIP[16]; // 扩容至16位适配最长IPv4地址
    int port;
    int NoOfNeig;
    char Neighbours[50];
} input;
    
int main()
{
    string mytext;
    int j = 0;
    ifstream MyReadFile("/home/wweckumarreddy/UDP/Project_Input/1.txt");
    // 新增文件打开状态校验
    if (!MyReadFile.is_open()) {
        cout << "文件打开失败,请检查路径、文件是否存在及访问权限" << endl;
        return 1;
    }
    // 仅需要处理前4行配置,无需额外r变量
    while (getline(MyReadFile, mytext) && j < 4)
    {
        if (j == 0) {
            strcpy(input.myIP, mytext.c_str());
            cout << "myIP = " << input.myIP << endl;
        } else if (j == 1) {
            istringstream(mytext) >> input.port;
            cout << "port = " << input.port << endl;
        } else if (j == 2) {
            istringstream(mytext) >> input.NoOfNeig;
            cout << "NoOfNeig = " << input.NoOfNeig << endl;
        } else if (j == 3) {
            strcpy(input.Neighbours, mytext.c_str());
            cout << "Neighbours = " << input.Neighbours << endl;
        }
        j++;
    }
    MyReadFile.close();
    return 0;
}

运行输出

修复后正常运行的输出如下:

myIP = 10.0.0.1
port = 4767
NoOfNeig = 3
Neighbours = 10.0.0.2 127.0.0.1 7238

内容的提问来源于stack exchange,提问作者Kranthi Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:54:04