I am currently working on an audio recording program. I ask the user to specify if they'd like to record or playback the recording... [recording -> user input = 1, playback -> user input = 2]. Moreover, I want to ensure the user inputs a number and not a letter. I have used isalpha and isdigit, but my output on the console is completely wrong.
int main() {
//VARIABLE DECLARATION
int mode = 0;
int t = 0;
FILE *fp;
if ((fp = fopen("recording.raw", "r"))==NULL) {
printf("NO RECORDING EXISTS...\nI WILL RECORD YOUR AUDIO FIRST!\n");
mode = 1;
}
else {
do {
printf("Please indicate if you would like to: \nRecord [1]\nPlayback [2]\nUSER CHOICE: ");
scanf("%d", &mode);
while (isalpha(mode)) {
printf("INVALID INPUT!\n");
printf("Please indicate if you would like to: \nRecord [1]\nPlayback [2]\nUSER CHOICE: ");
scanf("%d", &mode);
}
fclose(fp);
} while (mode != 1 && mode != 2);
}
if its only 1 or 2 you are looking to validate, you could change mode to char and check if it comes back as either 49 or 50 according to the ascii chart.
edit: and i think scanf with a char will only pick up the first digit/char entered so it may not need a length input check.
The problem is that you read the input as an int. When you enter an character the input gets rejected by scanf, the value of mode stays 0 and isalpha is always false.
Better to read the input into a char.
I changed it to a char, but now there is a null terminator appended to the end of users input. Now the program recognizes the users input of '1' as '1\0'. Is there a solution to removing the null terminator?
int main() {
//OPENING MATLAB ENGINE
/*Engine *m_pEngine;
m_pEngine = engOpen("null");*/
//VARIABLE DECLARATION
char mode;
int t = 0;
FILE *fp;
if ((fp = fopen("recording.raw", "r"))==NULL) {
printf("NO RECORDING EXISTS...\nI WILL RECORD YOUR AUDIO FIRST!\n");
mode = 1;
}
else {
do {
printf("Please indicate if you would like to: \nRecord [1]\nPlayback [2]\nUSER CHOICE: ");
scanf("%c", &mode);
fclose(fp);
} while (mode != 1 && mode != 2);
}
Thank you for your help! @Thomas1965
I have one more question...
I have a char variable, and I am attempting to make it into an int. After searching online, people mentioned I should do the following:
char t;
int time = t - '0';
After doing this I get a Run-Time Check failure. What is the reason for this?
Thanks in advance.