从文件中读取整数,中间有一个字符串
Reading integers from file, with a string in between
我有一个像这样的输入文件:
3 2
5 1
3 0
XXX
2 1
3 0
我需要分别读取每个整数,将其放入多项式中。"XXX"表示第二个多项式开始的位置。根据上面的例子,第一个多项式将是3x^2 + 5x^1 + 3x^0,第二个多项式将是2x^1 + 3x^0。
#include <iostream>
#include <iomanip>
#include <fstream>
#include "PolytermsP.h"
using namespace std;
int main()
{
// This will be an int
coefType coef;
// This will be an int
exponentType exponent;
// Polynomials
Poly a,b,remainder;
// After "XXX", I want this to be true
bool doneWithA = false;
// input/output files
ifstream input( "testfile1.txt" );
ofstream output( "output.txt" );
// Get the coefficient and exponent from the input file
input >> coef >> exponent;
// Make a term in polynomail a
a.setCoef( coef, exponent );
while( input )
{
if( input >> coef >> exponent )
{
if( doneWithA )
{
// We passed "XXX" so start putting terms into polynomial B instead of A
b.setCoef( exponent, coef );
} else {
// Put terms into polynomail A
a.setCoef( exponent, coef );
}
}
else
{
// Ran into "XXX"
doneWithA = true;
}
}
我遇到的问题是多项式A的值(在XXX之前)正在工作,但不适合b。
我要问的是:我如何使它,所以当我遇到"XXX",我可以设置"doneWithA"为真,并继续阅读文件后"XXX"?
我会把它们放在单独的循环中,因为你知道有两个,而且只有两个:
coefType coef; // This will be an int
exponentType exponent; // This will be an int
Poly a,b;
ifstream input( "testfile1.txt" );
while( input >> coef >> exponent )
a.setCoef( exponent, coef );
input.clear();
input.ignore(10, 'n');
while( input >> coef >> exponent )
b.setCoef( exponent, coef );
//other stuff
我认为最简单的方法是始终将输入读取为字符串,然后应用atoi(), http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/如果这个函数失败,那么你就得到了一个不是数字的字符串。"xxx"。
const string separator("XXX");
while(input){
string line;
getline(input,line);
if(line == separator)
doneWithA = true;
else {
istringstream input(line);
if(input >> coef >> exponent){
if(doneWithA)
b.setCoef( coef, exponent );
else
a.setCoef( coef, exponent );
}
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 我的输出中有一个额外的 0,为什么会这样
- 节点是否为空,即使它有一个值?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 在 Stream C++ 文本之前有一个额外的换行符
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- 从文件中读取整数,中间有一个字符串