As a part of my assignment I need to solve a problem in which I have to take space seperated inputs. I have already done my homework and stuck at a point where I have to take space seperated integers when number of integers are not predecided i.e whether there will be 2,5,10 or 15 integers.
I know that it can be done using arrays but in that case you need to predecide the number of integers.

Any help ?

What form does your data take?
If you have an input string as a pointer to a null-terminated array of char, you can just walk the string a find the spaces. So you would check the first char then increment the pointer and check the next char. Repeat until you get to the null. Either that or just just use an index into the array ( MyString[i] ) and just increment the index (i) until you get to the null.

What form does your data take?

I have to take integer inputs. They should be space separated. upon taking them I have to move to next line and again take space separated integer inputs.

Are you reading this input from the keyboard, or from a file, or will it be presented to you as some data object?

Are you reading this input from the keyboard, or from a file, or will it be presented to you as some data object?

From keyboard.

Or you can just walk the string from start to end, extracting the digits and detecting the spaces. But for class, tokenizing is popular (but also a popular way to get a SEGV fault, so handle pointers like knives). I always preferred non-destructive parsing using strptok() or the like. Are there rules about adjacent spaces, huge integers and other char values?

In the meantime I wrote a funtion to parse string and return digits to an integer array.
Here it is for future reference:
It takes two arguments:
1) char *str which is the string to be parsed.
2) int *num an integer array to store digits.
3) k is no of digits stored in array or array size.

   int parseStr(char *str,int *num){
        int temp=0,i=0,k=0;
        while(str[i]!='\0'){
            if(str[i]==' '){
                num[k++]=temp;
                temp=0;
            }else{
                temp=temp*10+(str[i]-48);           
                if(str[i+1]=='\0'){
                    num[k++]=temp;
                }
            }
            i++;
        }
        return k;
    }

Edited 1 Year Ago by Rahul47: edits

You need a 'digit_found' boolean flag so you do not print '0' for blanks and do print '0' for '0'. You start the parse with digit_found false and temp set to 0, for digits multiply temp by 10, add values and set the flag true, for spaces print the temp value if flag is true. Did anyone decide what to do about the other 244 values?

Edited 1 Year Ago by David_50

About digit_found.

We can add another condition statement if ASCII of str[i] lies in range of 48-57 to check for digits.

Edited 1 Year Ago by Rahul47: edits

This question has already been answered. Start a new discussion instead.