-1

so,i'm trying to do a conversion(integer to string) and then add this string with another.But it seems stringstream is not working..(it's normally working but the loop causes troubles) I'm done with google & almost tried everything but can't get this code to work..Anyone help me :( ?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
int n;
cin>>n;

string arr[n];
string a;
int i=0;
int s;
int c;

cin>>a;
arr[i] = a;
i++;
cout<<"OK"<<endl;
n--;

while(n--)
{
    cin>>a;
    s = 0;

    for(int j=0;j<i;j++)
    {
        if(arr[j] == a)
        {
            s = 1;
            break;
        }
    }

    i++;

    if(s == 0)
    {
        arr[i] = a;
        cout<<"OK"<<endl;
    }
    else
    {
        c++;
        stringstream ss;

        ss<<c;

        string m = ss.str();

        a+=m;

        arr[i] = a;

        cout<<a<<endl;

        ss.str("");
        ss.clear();
    }
}

return 0;
}
inhaler
  • 175
  • 1
  • 2
  • 12
  • If you're using C++11, you can use `std::to_string(i);` where `i` is an `int`. –  Jul 19 '16 at 11:55
  • 2
    It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: **[How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver Jul 19 '16 at 11:56
  • `string arr[n];` -- This is not valid `C++`, as arrays in C++ must use compile-time expressions to denote the number of items. – PaulMcKenzie Jul 19 '16 at 11:57
  • 2
    "`string stream` is not working". It is doing **something**. What is it doing? What do you expect it to do? What is the difference? – nugae Jul 19 '16 at 12:04
  • You're using an uninitialized variable `c`. – Barmar Jul 19 '16 at 12:20
  • No,i'm not using c++11 that's why all the trouble through stringstream @Tobias – inhaler Jul 19 '16 at 14:23
  • yes,i need it thank you &NathanOliver – inhaler Jul 19 '16 at 14:25
  • & i get the problem,thank u guys :) – inhaler Jul 19 '16 at 14:42

1 Answers1

0

c is uninitialized, you should initialize it, and also s before using:

int s = 0;
int c = 0;

You can't use non-const variables for array initialization, consider writing:

constexpr int MAX_STRINGS = 5;
string arr[MAX_STRINGS];

The loop trouble is here:

i++

You're going over the boundaries at the last element. Just move i++ to the end of while loop.

buld0zzr
  • 962
  • 5
  • 10