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