0

I have been trying to write a program that would read a sequence of space separated integers until the newline character is encountered.My approach was to read the input as a string and using atoi() to convert the string to integer. This is my approach:

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

int main()
{
int a[100],i=0,k=0;
char s[100];

//Read the first character
scanf("%c",&s[i]);

//Reads characters until new line character is encountered
while(s[i]!='\n'){
    i+=1;
    scanf("%c",&s[i]);
}

//Print the String
printf("\nstring = %s\n",s);

//Trying to convert the characters in the string to integer
for(i=0;s[i]!='\0';i++){
    if(isdigit(s[i]))
    {
        a[k] = atoi(s);
        k+=1;
    }
}

//Printing the integer array
for(i=0;i<k;i++)
printf("%d ",a[i]);
return 0;
}

But when I enter the input 1 2 3 4 the output is 1 1 1 1. All I want is to read the string and convert the characters of the string entered into terms of an Integer array a[0] = 1 a[1] = 2 a[3]= 3 a[4] = 4.I probably think a[k] = atoi(s) makes the reference to the first element in the string but not others.So every iteration is assigning a[k] = 1.How to get the desired result?

Thanks in advance.

Lingesh.K
  • 57
  • 2
  • 11

1 Answers1

1

this may help you

#include  <stdio.h>

int main() {
    const int array_max_size = 100;
    char symb;
    int arr[array_max_size];
    int array_current_size = 0;
    do {
        scanf("%d%c", &arr[array_current_size++], &symb);
    } while (symb != '\n');

    // printing array

    return 0;
}
bobra
  • 615
  • 3
  • 18
  • 2
    This will get fooled with input like `"123 456 \n"` as it assumes the `\n` directly follows the number – chux - Reinstate Monica Apr 10 '17 at 14:53
  • Sorry I should have mentioned before the newline character directly follows the number.But as mentioned what should I do if the input can take a newline character after the space? @chux – Lingesh.K Apr 10 '17 at 15:08
  • @Lingesh.K 1) Read in a line using `fgets()` with a generous buffer size and then parse the string for `int`s or 2) `scanf()` and `ungetc()` [example](http://stackoverflow.com/a/31845914/2410359) – chux - Reinstate Monica Apr 10 '17 at 15:12
  • @Lingesh.K Append "newline character directly follows the number" to the post if that is a requirement of input. – chux - Reinstate Monica Apr 10 '17 at 15:14