Home > front end >  What is causing the new line character to not work in my program?
What is causing the new line character to not work in my program?

Time:06-28

I am not sure why my new line is not working for printf(operand1, "%s\n"); I print test afterwards and its not on a new line.

#include <stdio.h>

int main(){
  printf("Enter elementary operation:"); //Output to console for user to see
  char input[32]; //Create a char array of size 32 characters (32 bytes or 256 bits), can only store 255 due to needing the end string character which is '\0'
  fgets(input, sizeof(input), stdin); //get line that user inputs
  printf(input,"%s\n"); //print the string the user input
  char operand1[32];
  int i = 0;

  while(input[i] == '0' || input[i] == '.' || input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4'
|| input[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9' || (i == 0 && input[i] == '-')){

    operand1[i] = input[i];
    i  ;

  }

  printf(operand1, "%s\n");
  printf("test");
  return 0;
}

Output is:

Enter elementary operation:99 0

99 0

99test%

CodePudding user response:

First, it should be printf("%s\n",operand1). What happens in your code is that operand1 is treated as format string and since it doesn't have % in it, it is printed as is.

Second, your operand1 doesn't have zero byte after the copied chars, so it's not really a string from C's point of view and when you pass it to printf with %s format option printf will print your memory content until it accidentally hits a 0. Although, perhaps this behavior won't happen, because when you allocate an array it might be pre-initialized with zeros - depends on lots of things. It is more correct and safe to add operand1[i] = '\0' after the loop

Third, there is isdigit function (defined in <ctype.h>), that you can use i/o testing manually for all the digits. Or you can use comparison (input[i] >= '0' && input[i] <= '9')

  • Related