Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is causing the new line character to not work in my program?

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 newline.

#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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

99test%

>Solution :

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')

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading