c++ - 读取文件时我的 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++ 中循环 eof 是一个非常糟糕的主意。如果您的文件为空,fin.eof()
则在您尝试从中读取内容之前将是错误的。
因此,作为第一个纠正措施更改为:
while(fin >> temp)
{
....
}
然后我们假设它temp
被定义为char
,因为您逐个字符地读取字符。
问题是它>>
往往会吞下很多空格,包括你永远不会得到的 ' ' 和 '\n' 。如果您确实希望得到一些白色,则需要设置std::noskipws
:
while(fin >> noskipws >> temp)
{
....
}
但是,如果您正在逐个字符地阅读,更好的方法可能是阅读fin.get()
推荐阅读
- python - 有没有办法让我用不同的元素循环附加函数?
- javascript - JS显示Div需要2次点击
- java - 打印结果集不显示所有行
- python - 扩展实例装饰器以获取键值参数?
- python - 如何根据 PyMC3 中的另一个值测量一个值的贝叶斯不确定性
- javascript - 映射时如何使用onClick
- python - Matplotlib 图和 PyQt5/PySide2 QSplitter Widget 之间的问题
- javascript - reactJS中的Firebase初始化问题
- google-oauth - google-api-js-client (gapi) 如何跨会话和刷新恢复登录状态
- android - 单击带有recyclerview的项目片段时如何将数据传递给活动