0

Hey guys I want to take 7 numbers from the user, preferrably into an array. The problem is I want the numbers to be able to be taken regardless of whitespace, so 1234567 should be the same as 123 45 6 7 and etc..

I currently have this code that works but was wondering if there is an easier or more efficient way I could do this, perhaps by taking input with scanf() then removing the spaces later? Thanks!

while(i<7){
    temp = getchar();

    if(temp != ' '){
        arr[i] = temp;
        i++;            
    }
}
J...S
  • 5,079
  • 1
  • 20
  • 35
dirlik
  • 35
  • 6
  • Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. https://stackoverflow.com/help/on-topic – Rob Mar 10 '18 at 16:34
  • *"I want to take 7 numbers from the user,"* - By numbers, you mean *digit characters* ? That is all this code does. Rather, if your intent was to actually store the integer values `123`, then `45`, then `6`, then `7`, your algorithm certainly won't do that, and the task itself requires an input format predisposition. – WhozCraig Mar 10 '18 at 17:17
  • Yes I meant digit characters, sorry for not being clear enough. – dirlik Mar 11 '18 at 17:18

1 Answers1

1

With scanf() you could do

for(int i=0; i<7; ++i)
{
    scanf(" %c", &arr[i]);
}

The leading space in the scanf format string will match any any number of whitespace characters (zero or more) in between.

Have a look at this post.

J...S
  • 5,079
  • 1
  • 20
  • 35