1 / 2
Jul 2017

Hello everyone! This is the issue I'm struggling with since I started doing tasks on Polish SPOJ. A lot of them has an input in a form of values divided by spaces (like "1 53 23").
I've made a simple trick allowing me to avoid using array and knowing how many values are in my string. I read the values as a string using std::getline, then I convert string into stringstream and create a loop while( stream >> n )
The results I get on my GCC compiler are perfectly fine, however sending my code to IDEone always ends up badly.
I honestly don't know how to move forward, I feel like I'm leaving out something important and obvious. Input always gives you a quantity of values in the next test phase, but I feel like it's easier to perform it without knowing that quantity value.
I'm desperate for help. I asked my a-little-more-experienced friends about it and their codes looks even more complicated and ominous. Here I attach my tries, so you can have better view on my attempts:
std::getline( std::cin, input );
std::stringstream stream( input );
while( stream >> n )
{
result += n;
n = 0;
}
std::cout << result << std::endl;

  • created

    Jul '17
  • last reply

    Jul '17
  • 1

    reply

  • 743

    views

  • 2

    users

i don't get what the problem is...?
if you want to read some numbers (endless loop) from the input, you can do sth like this:

int x;
while(cin>>x)
{
//doing something with number
}

for example you have some numbers in input (you don't know how many) and the output is the sum of them
then you write sth like this:

int x,sum=0;
while(cin>>x)
{
sum+=x;
}
cout<<sum<<endl;

so... example with numbers:

input : 2 6 33 67 12 54
output: 174
=====================
I don't get it why you need to write string to values array or whatever...
if you want to write values into integer array, (let's say there won't be more than 100 values) then you can just:

int x, array[100];
int i=0;
while(cin>>x)
{
array[i]=x;
i++;
if(i==100) break;
}