0

I want to enter numbered objects into an array. Each object's element has to be numbered depending on its position on the array. I can't figure out why the string index keeps the previous values when it is converted as the loop goes on. For example. First place is 0 and as the loop goes on its becomes 01,012,0123 and so on. here's that part of the code I have problem with

 stringstream convert; 
    int N;
    int k;
srand ((long) 123456);
N=rand()%100+1;
NewTable=new Employee[N];


for(k=0;k<N;k++){
    string name,surname,number="";
    convert<<k;
    number=convert.str();
    cout<<number;
    name="John_"+number;
    surname="John_"+number;
    NewTable[k].SetEmployee(name,surname,13*k,3*k);*/

}

I also thought that by reinitializing the string of the number at the the start of the loop it will solve the problem, but it didn't.

Sot Tso
  • 13
  • 1

2 Answers2

0

You're not clearing the stringstream buffer and thus appending stuff to it at every iteration

for (k = 0; k<N; k++){
    string name, surname, number = "";
    convert.str(""); // You should reset its contents
    convert << k;
    number = convert.str();

Edit: or, as James noted, it might be better to re-create the stringstream each time if there's more involved (furthermore you only posted a snippet of code):

for (k = 0; k<N; k++){
    string name, surname, number = "";
    std::ostringstream convert;
    convert << k;
    number = convert.str();
Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • This isn't 100% sure; there's more state than that in a stream. The best solution is to just create a new `std::ostringstream` each time in the loop. – James Kanze Oct 17 '14 at 09:17
  • I decided to create a new std::ostringstream in each loop. Thank you both for your answers – Sot Tso Oct 17 '14 at 09:27
0

If you want a virgin std::ostringstream each time in the loop, then just create a new one each time in the loop. Although theoretically, you can reset everything to get the stream back into a virgin state, it's far from trivial, and not necessarily 100% sure. The simplest is just:

for ( int k = 0; k < N; ++k ) {
    std::ostringstream convert;
    convert << k;
    std::string number = convert.str();
    //  ...
}

(As a general rule, it's best not to define a variable until you need it, and to initialize it immediately in the definition.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329