0

All I want is a user input for the array foo and print op, left, and right from it.

I tried adding the following code, but can't get the same result.

Instead of writing char foo [29] = "1021+2551"; I wrote:

int i;

printf("Enter the number and opperator");

for(i=0; i<1; i++)      // I used i < 1 b/c I want to get only one line input

{

scanf("%c", foo[i]);

}


void main(){

    int index;
    char foo[29] = "1021+2551";
    int len = strlen(foo);

    for (int i=0; i < len; i++)
    {
    if(foo[i] == '+' || foo[i] == '-' || foo[i] == '*' || foo[i] == '/' || foo[i] == '%'){
       char op = foo[i];
       printf("%c", op);
       index = i;
        }
    }
    char left;
    for(int j=0; j < index; j++){
       left = printf("%c",foo[j]);
    }
    char right;
    for(int k=index + 1; k < len; k++){
       right = printf("%c",foo[k]);
    }
}

If I enter 100+200 in the user input the result should be

+100200

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Brook
  • 21
  • 7
  • That could be because `char foo [29] = "1021+2551"` does not contain the newlines that `scanf("%c", foo[i])` will. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). But I can't see why you want a loop inputting only one character. Have you tried using `fgets` to input a single line? – Weather Vane Jan 23 '19 at 20:31

1 Answers1

2

Something like this simple and quick :)

    int main(){

    int i;
    char foo[29];

    printf("Enter the number and opperator\n");
    fgets(foo, 29 , stdin);

    int index;
    int len = strlen(foo);

    for (int i=0; i < len; i++)
    {
    if(foo[i] == '+' || foo[i] == '-' || foo[i] == '*' || foo[i] == '/' || foo[i] == '%'){
       char op = foo[i];
       printf("%c", op);
       index = i;
        }
    } printf(" ");
    char left;
    for(int j=0; j < index; j++){
       left = printf("%c",foo[j]);
    } printf(" ");
    char right;
    for(int k=index + 1; k < len; k++){
       right = printf("%c",foo[k]);
    }
    return 0;
}
Spinkoo
  • 2,080
  • 1
  • 7
  • 23
  • 1
    Note, that `scanf("%s",foo);` shouldn't be advised. It's better to use `scanf("%28s",foo);` to set the max character size. But remember - scanf will read up to a space. To handle spaces, one could use `fgets`. – KamilCuk Jan 23 '19 at 20:47
  • thanks, it worked. Also what if I want to print left or right or op separately out side the for loop? Can I say printf("%c", right); ? – Brook Jan 23 '19 at 20:57
  • well given the structure you are using my opinion would be to let it in the for loop otherwise you will have to be making copies this is why : 1- printf("%c",character) will print the one character you assign to it & not the whole string of characters so you either copy it in a char array or leave it this way with a loop :) – Spinkoo Jan 23 '19 at 21:24