2021年4月5日星期一

Parse User input string in C (using Visual Studio 2019)

I'm having a really strange situation when I use Visual Studio 2019 to write C program.

My homework is: Write a program that asks the user to enter a string in the format of "name=value". Then check the user input, if the format is valid. The name could have a maximum of 31characters. The value could have a maximum of 127characters. If there is something wrong with the input (eg no "=" sign, string too long, missing name, etc) the program should exit with an error message. For example: Please enter a string in the format of "name=value": place=Mannheim //example of user input

If the input is correct your program should ...

  1. copy the first part of the input string(the name) to a string variable
  2. copy the second part of the input string(the value) to a string variable
  3. output both strings to console in this form: name: place value: Mannheim

Below is my code:

#include <stdio.h>  // standard input/output functions  #include <string.h>  #define N 159    int main(void)  {      char string[N];      char* equalsign;      char* lastnull;      int i, j;        // user input      printf("Please enter a string in the format of 'name=value':\n");      scanf_s("%s", string, N);           // find the position of '='      equalsign = strchr(string, '=');      // find the position of the end 'NULL'      lastnull=strrchr(string, NULL);        // check the user input      if (equalsign == NULL)      {          printf("The input is wrong, there is no '='");      }      else      {          while ((equalsign - string) > 31)          {              printf("The input is wrong, name is more than 31 characters");          }                while ((lastnull - equalsign - 1) > 127)          {              printf("The input is wrong, name is more than 127 characters");          }            }           // output      printf("name: ");      for (i = 0; i < (equalsign - string); i++)       {                printf("%c", string[i]);      }        printf("\n");            printf("value: ");      for (j = (equalsign - string + 1); j < (lastnull - string); j++)       {                printf("%c", string[j]);      }              return 0;  }  

However, when I debug this code, it shows a lot of strange mistake, such as "}" of else is wrong, "for" is wrong, even return is wrong.

Can anybody tells me why that happened, is there anything wrong with my code? Because when I use "Dev-C++" to debug the same code, it runs very well and shows the desired result.

Here is the screenshot after I debug this code: enter image description here

Also, if there are any other solutions please tell me, but only with the basic things since I only learn C for 2 months.

Thank you.

https://stackoverflow.com/questions/66961157/parse-user-input-string-in-c-using-visual-studio-2019 April 06, 2021 at 08:02AM

没有评论:

发表评论