2

I'm trying to ask the user for an input of say, 3 characters. I want to separate the first character and the last two from each other. So if "A13" is a user input, I want to store 'A' in a separate char and "13" in a separate char[].

//initializations
char seatName[4], seatRowName, seatNumber[3];

printf("\n\nPick a seat (Row Seat) ");
scanf("%s", seatName);
seatRowName=seatName[0];
seatNumber=strchr(seatName, seatRowName);
//I get the "error: incompatible types in assignment" on the above line

Sample output:

Pick a seat (Row Seat): A13
//seatRowName = A, seatNumber=13

turing042
  • 99
  • 10
  • 1
    You already have what you need. `*seatName` is `'A'` and `seatName + 1` is `"13"`. – David C. Rankin May 02 '19 at 05:47
  • 1
    Use the *field-width* modifier `"%3s"` to protect the array bounds of `seatName` from overrun if there is an accidental additional key entered -- otherwise you invoke *Undefined Behavior*. (additionally, -- *don't skimp on buffer size*, `32` instead of `4` would be a more realistic minimum) – David C. Rankin May 02 '19 at 06:01

1 Answers1

2

Use below code:

seatRowName=seatName[0];
strcpy(seatNumber, &seatName[1]);  // strncpy if you want to be safe

If you would never change seatName, you can also use const char *seatNumber = &seatName[1];


Why does it work:

             +0  +1  +2  +3
            +---+---+---+---+
   seatName | A | 1 | 3 | \0|
            +---+---+---+---+
             [0] [1] [2] [3]

In memory seatName stores the content in contiguous space. This approach would work fine even for inputs like A3. You should provide other sanity checks to input.

seatNumber=strchr(seatName, seatRowName);

I get the "error: incompatible types in assignment" on the above line

strchr returns char * and type of seatNumber is char [3]. Because types of RHS and LHS are different you are getting above error. Unlike many popular languages C doesn't allow this.

Assigning apples to oranges is almost always incorrect. strcpy(A, B); instead of A = B would work in this case.

Gyapti Jain
  • 4,056
  • 20
  • 40