0

I know that getline is C++ standard but I need to read a line of digits:

123856

and save it to an array. But how to do this without spaces between given (as input) digits? I want a user input to be:

123856 (with no spaces) and then save it to an array (n element array) and after that, I want my array to look like this:

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 8;
array[4] = 5;
array[5] = 6;

But how to make it in C, without a getline?

This is NOT what I want:

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>

int main(int argc, char **argv)
{
    int t[4];
    int i;

    for(i=0; i<4; i++)
        scanf("%d", &t[i]);
    for(i=0; i<4; i++)
        printf("%d\n", t[i]);

    return 0;
}
yak
  • 3,770
  • 19
  • 60
  • 111

6 Answers6

3

If I understood you correct, the following should do it:

  1. read the whole line
  2. loop through the string as long as you get digits or the string ends
  3. for every digit, place it's value in your array and increase the index by 1
junix
  • 3,161
  • 13
  • 27
  • Ok, you edited your question while I was writing :-) If it's a requirement to not use getline, read character by character as long as you get digits and place them in an array. – junix Jan 23 '13 at 14:06
  • @WilliamPursell Why is it pointless? Yak's requirement is to read a line of digits. Assuming EOL is also end of his line of digits, he can save many CPU cycles by reading the buffer at once instead of polling for single digits. – junix Jan 23 '13 at 14:12
  • Reading single chars with getchar will only invoke one system call, but it allows the system to handle all the buffering for you and requires less code. – William Pursell Jan 23 '13 at 14:15
  • Yak's requirement is to get a line of characters into an array. Yak's problem is that Yak thinks an entire line must be read. – William Pursell Jan 23 '13 at 14:17
  • It still at least invokes `getchar` itself for every character to be read. Of course the impact of this depends on the size of the dataset to be read. – junix Jan 23 '13 at 14:18
  • Both answers have merits and without proper testing you are not gonna resolve this. Why not drop it? ]:) – Dariusz Jan 23 '13 at 14:23
3
while( ( c = getchar()) != EOF  &&  c != '\n' &&  i < max ) {
    /* If desired, add check for value outside of 0-9 */
    array[ i++ ] = c - '0';
    ...
}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    After this edit you got it a bit wrong actually - what do you think sizeof (array) does? that's very dangerous... – Dariusz Jan 23 '13 at 14:18
  • @WilliamPursell Please note that this only works for arrays "on stack" not for dynamically allocated arrays. I think that's what Dariusz meant. – junix Jan 23 '13 at 14:28
  • sizeof array returns the size of the array. If array is a pointer, this will indeed fail miserably. If array is an array, it works just fine. Perhaps a simpler bounds check should be used to prevent any confusion. – William Pursell Jan 23 '13 at 14:32
  • @WilliamPursell Just to avoid confusion: There is no real difference between arrays and pointers. This will fail already if I allocate an array dynamically. – junix Jan 23 '13 at 14:48
  • There is a real difference between arrays and pointers. Pointers address memory. Arrays span memroy. Given `int *x, y[ 50 ]`, `sizeof x == sizeof( int * )`, `sizeof *x == sizeof( int )`, and `sizeof y == 50 * sizeof( int )`. When passed as a parameter, arrays decay to a pointer to the first element, and the syntax of the language often allows the name of an array to be used interchangeably with a pointer to the array, but they are different things. – William Pursell Jan 23 '13 at 17:06
1
char arr[] = "1234567";
int intarr[10];

int count = 0;
for (char* ptr = arr; *ptr; ptr++) {
  intarr[count] = *ptr - '0';
  count++;
}
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • 2
    Maybe the code becomes more readable if you would write ''intarr[count] = *ptr - '0';'' instead of the hard coded ASCII value... Of course it should also be paid attention that the length of the array is not exceeded... – junix Jan 23 '13 at 14:08
  • @junix '0' right. Rest - this is a fast simple answer, no point making several ifs to check various conditions. Let the guy do some work by himself – Dariusz Jan 23 '13 at 14:10
  • Yes, but who says that the guy is aware of the nasty side effects? ;-) Just wanted to mention that this is not a "drop in" solution and needs some more thinking. – junix Jan 23 '13 at 14:15
  • Sorry, didn't notice that ;-) – junix Jan 23 '13 at 14:19
0

try this

#include <stdio.h>
#include <string.h>

 main (int argc, char *argv[])
{

    FILE *f;


    int i=0;
    int j=0;
    char output[100];
    char* output1[100];
    char string[100];
    char delims1[] = " ";
    char delims2[] = "*";
    char* result = NULL;
    char* result3 = NULL;
    int num;



//for (j=0; j<2; j++)
//{
    //printf("%s",delims9[6]);
//}

f = fopen("text.txt","r");
   //
    while( fgets(string,sizeof(string),f) )
    {

        result = strtok( string, delims1 );

        while( result != NULL )
        {
            output1[i]=result;
          printf("%s\n",output1[i]);
          result = strtok( NULL, delims1 );
            i++;

        }

    for (num = 0; num < 100; i++ )      //
    {                                   // Error On this array
        printf("%s\n", output1[i]);     //
    }                                   //


    }
printf("\n%d",i/3+1);



    return 0 ;
}
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
0

Ok, without using any string.

int digits = 123856;
int numofdigits = 1 + floor(log10(digits));

int digits_arr[numofdigits];
int i;
for(i = numofdigits-1; i >= 0; i--) {
    digits_arr[i] = (int)floor(digits / pow(10, i)) % 10;
}
n1xx1
  • 1,971
  • 20
  • 26
-1

Try the below link... Same question asked here and get solution....

convert an integer number into an array

char * convertNumberIntoArray(unsigned int number) {
    unsigned int length = (int)(log10((float)number)) + 1;
    char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
    do {
        *curr++ = number % 10;
        number /= 10;
    } while (number != 0);
    return arr;
}
Community
  • 1
  • 1
Pandian
  • 8,848
  • 2
  • 23
  • 33
  • You missed the point: The number is already existing as string. There is no need to convert it into a string. The other thing is that the conversion you do is very expensive in terms of cpu cycles. – junix Jan 23 '13 at 14:23