简体   繁体   中英

How to convert a string into an integer without white spaces?

I am trying to multiply complex numbers that is inputted by a user. Some example inputs would be :

Enter a complex number in the form ai + b: 2i + 8

Enter a complex number in the form ai + b: 11 i + 2

Enter a complex number in the form ai + b: 1i+6

I want these all to be valid inputs but am not sure how to make sure that scanf() ignores spaces and the characters so that I can just extract the integers. I am trying to do this by having scanf() accepting the input as three strings with the first string containing ai, the second string containing the '+', and the third string containing b. However, my code trying to turn my first string (with ai) into an integer (just a without 'i') is not successful.

int inta(char* ai){
  int i;
  int origa;
  int max;
  int a = 0;
  for(i = 0; i<strlen(ai); i++){
    if(ai[i] != "i" && ai[i] != ' ')
      continue;
    else
      break;
  }
  if(i > 1)
    for(max = i; max > 0; max--){
      origa = atoi(ai[max])*pow(10, max);
      a = origa + a;
    }
  else
    a = atoi(ai[0]);
  return a;
}

UPDATE


Ok , Try these two functions to remove spaces from any string.



    char* erase(char*str, int index)
    {
        int i = index;
        while (str[i] != '\0')
        {
            str[i] = str[i + 1];
            i++;
        }
        return str;
    }
    char* remove_spaces(char* str)
    {
        int i = 0;
        while (str[i] != '\0')
        {
            if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n')
            {
                erase(str, i);
                i--;
            }
            i++;

        }
        return str;
    }

Then for any character you want to convert it to int you can subtract '0' from it.


Try this code


    int x;
    x='5'-'0'
    printf("%d",x);

The output for this will be integer value = 5 .


For your case , the first string has (ai) so if you want to convert it to number you can just select the first char "ie: str[0]" and subtract '0' from it.

or you can use my custom function to convert any string to integer but you should check that the string contains only digits before calling this function , and also pass the address of the integer that you want it to hold the result.


for example:


    void convert_to_int(char*str,int*result)
    {
        int i=strlen(str)-1;
        *result = 0;
        int factor = 1;
        while (i >= 0)
        {
            (*result) += (str[i]-'0') * factor;
            factor *= 10;
            i--;
        }
    }
    int main()
    {
    int x;
    convert_to_int(str,&x);
    return 0;
    }

To extract a from a string ai+b even with a space between the value of a and the 'i' just use sscanf and check it returns 1 to verify you read an int

And finally to also extract the operator and b just do

sscanf(argv[1], "%d i %c %d", &a, &oper, &b)

and check it returns 3 more oper is valid, for instance :

#include <stdio.h>

int main(int argc, char ** argv)
{
  int a, b;
  char oper;

  if (argc != 2)
    printf("Usage: %s <ai+b>\n", *argv);
  else if ((sscanf(argv[1], "%d i %c %d", &a, &oper, &b) == 3)
           && ((oper == '+') || (oper == '-')))
    printf("a=%d b=%d oper=%c\n", a, b, oper);
  else
    puts("invalid input");

  return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
a=12 b=3 oper=-
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $ 

Note I allow to enter directly 1i-2 rather than to force to enter 1i+-2 less practical because I allow the operator to be '-', if you do not want to allow that simplified form :

#include <stdio.h>

int main(int argc, char ** argv)
{
  int a, b;

  if (argc != 2)
    printf("Usage: %s <ai+b>\n", *argv);
  else if (sscanf(argv[1], "%d i + %d", &a, &b) == 2)
    printf("a=%d b=%d\n", a, b);
  else
    puts("invalid input");

  return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "-12i++3"
a=-12 b=3 oper=+
pi@raspberrypi:/tmp $ 

About your update, your input strings for sscanf are invalid because you give NULL pointers, you want something like that :

#include <stdio.h>

int main()
{
  char line[64];
  int a;
  int b;
  int c;
  int d;
  int finala;
  int finalb;

  printf("Enter the first complex number in the form ai + b: ");

  if ((fgets(line, sizeof(line), stdin) == NULL) ||
      (sscanf(line, "%d i + %d", &a, &b) != 2)) {
    puts("invalid form");
    return -1;
  }

  printf("Enter the second complex number in the form ai + b: ");
  if ((fgets(line, sizeof(line), stdin) == NULL) ||
      (sscanf(line, "%d i + %d", &c, &d) != 2)) {
    puts("invalid form");
    return -1;
  }

  finala = b*c + a*d;
  finalb = b*d + a*c*(-1);

  printf("(%di + %d) * (%di + %d) = %di + %d\n", a, b, c, d, finala, finalb);
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the first complex number in the form ai + b: 1i+2
Enter the second complex number in the form ai + b: -2i+6
(1i + 2) * (-2i + 6) = 2i + 14
pi@raspberrypi:/tmp $ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM