读取文件中传递的值
Reading a value that is passed in a file
我正在阅读C 中的一个文件,我按空格分开值,然后像这样输入
1 2
3 4
5 6
我正在检查第二部分,如果是6,我想 cout
整个行。
5 6
代码样本:
ifstream f;
f.open("sample.txt");
f>>check;
if(check==6){
cout << check;
}
如何打印整行而无需存储?要明确我只想打印当前值和最后一个值。
因为您想比较数据,然后根据比较结果做点什么,您可以 not 避免将它们存储在某个地方。
如果要打印整个行,则必须存储它:
struct Record
{
int first;
int second;
std::istream& operator>>(std::istream& input, Record& r);
};
std::istream& operator>>(std::istream& input, Record& r)
{
input >> r.first;
input >> r.second;
};
//...
Record r;
while (f >> r)
{
if (r.second == 6)
{
std::cout << r.first << " " << r.second << "n";
}
}
在上面的代码中,我使用struct
建模输入行。读取和存储两个值。当第二个值为6时,第一个和第二个值是输出。
您不需要struct
,但是可以使用两个变量:
int first;
int second;
while (f >> first >> second)
{
if (second == 6)
{
std::cout << first << " " << second << "n";
}
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量