首页 > 解决方案 > 读取文件时我的 if 语句不起作用

问题描述

在此代码中,我不知道为什么但if (temp == '\n')不起作用,因此在输出中全为零,并且第 i 个索引中的零不会更新

while(fin.eof() != 1)
{
    if(temp ==  '\n' ) 
    {
        k = 0;
        j = 0;
        i++;
        cout << "call from 2nd if";     
    }
    if(temp == ',')
    {
        k = 0;
        j++;
        cout << "call from 1st if";
    }
    fin >> temp; 
    data[i][j][k] = temp;
    
    cout << "address " << i << j << k << " : " << data[i][j][k] << endl;
    k++;
    i,j;
}

输出:

   address at **0**31 : u
   address at **0**32 : i
   address at **0**33 : c
   address at **0**34 : e
   address at **0**35 : B
   .
   .
   .

基本上它是 3dimesnional 数组,其中 i th 值没有更新,对此有什么解决方案

标签: c++if-statementfile-handlingifstream

解决方案


在 C++ 中循环 eof 是一个非常糟糕的主意。如果您的文件为空,fin.eof()则在您尝试从中读取内容之前将是错误的。

因此,作为第一个纠正措施更改为:

while(fin >> temp)
{
    ....
} 

然后我们假设它temp被定义为char,因为您逐个字符地读取字符。

问题是它>>往往会吞下很多空格,包括你永远不会得到的 ' ' 和 '\n' 。如果您确实希望得到一些白色,则需要设置std::noskipws

while(fin >> noskipws >> temp)
{
    ....
} 

但是,如果您正在逐个字符地阅读,更好的方法可能是阅读fin.get()


推荐阅读