Đề bài là nếu người dùng nhập quá 2 tokens hay chiều dài chuỗi quá 20 kí tự thì thông báo lỗi và quay về nhập lại. Nếu nhập đúng thì xét tokens. Nếu token là số thì in ra “INT” hay chuỗi thì in ra “STR”. Nếu người dùng nhập vào “quit” thì thoát khỏi chương trình.
Đây là test của mình. Mình bị lỗi nếu người dùng nhập vào kí tự khoảng trắng nhiều lần
one two three
ERROR! Incorrect number of tokens found.
ERROR! Incorrect number of tokens found.
becareful of spaces at end of the line
ERROR! Input string too long.
heres 3
STR INT
heres 20
ERROR! Input string too long.
12345678901234567890
ERROR! Input string too long.
123456789012345678901
ERROR! Input string too long.
1
qUit
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
int is_digit(char);
void stdin_flush();
int main ()
{
printf("Assignment #1-4, Huy Nguyen, [email protected]\n");
int is_digit(char *a){
int isDigit = 0;
int i = 0;
while (i < strlen(a) && isDigit == 0){
if (a[i] >= '0' && a[i] <= '9')
isDigit = 0;
else
isDigit = 1;
i++;
}
return isDigit;
}
void stdin_flush(){
int c;
while ((c = getchar()) != '\n' && c != EOF) {};
}
char str[256];
char *ptr;
char *ptr2;
char **b = (char **)malloc(256*sizeof(char));
char *p;
int count =0;
int index;
int j =0;
int num_space;
do{
do{
count = 0;
index = 0;
num_space = -1;
//stdin_flush();
printf("> ");
fgets(str,66,stdin);
if (strlen(str)>20){
printf("ERROR! Input string too long.\n");
continue;
}
str[strlen(str)-1] = '\0';
ptr = str;
while (*ptr != '\0'){
if (*ptr == ' '){
num_space++;
}
ptr++;
}
p = strtok(str," ");
while (p != NULL){
b[index] = p;
count++;
index++;
p = strtok(NULL," ");
}
if (count > 2 || count <= 0){
printf("ERROR! Incorrect number of tokens found.\n");
}
ptr = str;
}while(count > 2 || count <= 0);
while (j < index){
if (is_digit(b[j]) == 0)
printf("INT ");
else
printf("STR ");
j++;
}
printf("\n");
}while(strcasecmp(str,"quit"));
return 0;
}