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.