文件I/O c++ ifstream语法
File I/O C++ ifstream syntax
我正在尝试编写一个程序,该程序将读取文本文件并执行它在文本文件中读取的数学操作。
的例子:+ 45 35
我正在使用一个输入流来读取该文本块,并在函数中的数字之前执行一个数学运算。
我找了一个多小时才找到正确的语法,我都快抓狂了。
我完全困在弄清楚如何让流函数读取每个字符,直到空白,但它一次读取一个字符,getline甚至不是一个可识别的函数,我认为这将有助于我的事业。
这是我正在使用的,每次读取一个字符
char ch;
inFile >> ch;
命令流读取文本块直到它达到空白的正确语法是什么,谁能建议我如何通过将文本文件中的数字加在一起?
是否有一个特定的原因,你是固定使用文本块,而不是在值读取?
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream inf(" + 42 100");
char op;
int num1, num2;
inf >> op >> num1 >> num2;
cout << "Op: " << op << endl;
cout << "Num1: " << num1 << endl;
cout << "Num2: " << num2 << endl;
// pin the op-char to the first operand
istringstream inf2("-43 101");
inf2 >> op >> num1 >> num2;
cout << "Op: " << op << endl;
cout << "Num1: " << num1 << endl;
cout << "Num2: " << num2 << endl;
return 0;
}
Op: +
Num1: 42
Num2: 100
Op: -
Num1: 43
Num2: 101
如果你想在保证每行只有一个op和两个操作数的输入文件中这样做,它将是这样的:
ifstream inf(fname);
char op;
int o1, o2;
while (inf >> op >> o1 >> o2)
{
// use your op and operands here.
// switch (op)... etc.
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- ifstream什么都没读
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- ifstream文件在从行中读取时被清除
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 使用基类指针调用基类的值构造函数的语法是什么?
- 将 ifstream 拆分为 n 个流?
- 很好的语法来获取对向量/数组数据的大小引用?
- 文件I/O c++ ifstream语法
- 使用ifstream时出现语法错误