我的c++程序在我不告诉他的地方连接字符串

My c++ program concatenates strings where i dont tell him to

本文关键字:方连接 连接 字符串 程序 c++ 告诉他 我的      更新时间:2023-10-16

嗨,我正在为我在c++上的一个家庭作业编写这个小程序。它是关于多项式的,它要求多项式的次数、指数、系数和常数来乘以系数。现在我有了我一直在做的代码:

#include <iostream>
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
using namespace std;
int main ()
{    
    int deg=0, x=0, con, co;
    string m, n, poli="";
    ostringstream convert, convert1;
    cout<<"Hi! this program will show the resulting polynomial of multiplying the npolynomial times the constant.nn";
    cout<<" ";
    cout<<"nnBut first give me the degree of the polynomial (max 9): "; cin>>deg;
    cout<<"nnNow the Multiplier constant: "; cin>>con;
    cout<<"nnNow give me the coefficients of the polynomial.n";
    while(deg!=0){
        int n1=0, n2=0, n3=0;
        string m="", n="";
        convert.clear();
        convert1.clear();
        cout<<"Exponent " << deg <<" coefficient: "; cin >>co; cout<<"nn";
        if(co!=0){
            n2=(co*con);
            n3=(deg+0);
            convert << n2;
            convert1 << n3;
            m = convert.str();
            n = convert1.str();
            poli+=m+"x^"+n+" ";
            cout<<poli+"nn";        
        }
        deg--;
    }
}

但出于某种原因,比如说3x^4 2x^3 2x2

... it out puts

3x^4 32x^43 322x^432

正如你所看到的,它是由于某种原因连接在一起的,我不知道为什么,你们能帮我吗?

您似乎误解了std::basic_ios::clear`函数的作用。它不清除流缓冲区。这意味着每次你做

convert << n2;
convert1 << n3;

正在附加到流中。

要解决此问题,请将流变量convertconvert1设置为循环内部的本地变量,就像mn一样。

我已经声明了'ostingstream convert,convert1;'在while循环中,它在这里工作得很好。每次while循环迭代后,流都没有清除。