Mình đang viết 1 chương trình đòi user nhập vào một chuỗi kí tự và in chuỗi kí tự đó ra màn hình. Điều kiện là chuỗi đó không có quá 20 kí tự và 2 dấu space. User sẽ nhập tiếp tục nếu thỏa 2 điều kiện trên. Để kết thúc chương trình, user sẽ đánh “quit”. Mình không biết làm cách nào để chương trình chạy cho tới khi thỏa điều kiện trên.
char str[256];
char *ptr;
char *end_ptr;
char **tokens;
char temp;
int num_chars = 0;
int num_tokens = 0;
int num_spaces = 0;
scanf("> %65[^\n]%*c", str);
//fgets(str,65,stdin);
str[strlen(str)+1] = '\0';
ptr = str;
while (*ptr != '\0'){
if (*ptr == ' ')
{
num_spaces++;
}
ptr++;
}
printf("Num spaces %d \n",num_spaces);
fflush(NULL);
int checkSpaces(int spaces){
char *strPtr;
if (spaces >= 2)
return 1;
else
return 0;
}
void checkQuit (char *b){
char temp[4];
int i = 0;
while (i<4){
temp[i] = tolower(b[i]);
i++;
}
char cmpQuit[] = {'q','u','i','t'};
int count = 0;
int j = 0;
while (j < 4){
if (temp[j] == cmpQuit[j]){
count++;
}
j++;
}
if (count = 4){
printf("Good bye!!!");
exit (0);
}
}
int checkNumSpaces = checkSpaces(num_spaces);
do{
scanf("> %65[^\n]%*c", str);
//fgets(str,65,stdin);
str[strlen(str)+1] = '\0';
ptr = str;
while (*ptr != '\0'){
if (*ptr == ' ')
{
num_spaces++;
}
ptr++;
}
while (checkNumSpaces != 0 || (int)strlen(str) > 21){
while(checkNumSpaces){
printf("ERROR! Incorrect number of tokens found. \n");
scanf("> %65[^\n]%*c", str);
ptr=str;
str[strlen(str)+1] = '\0';
num_spaces = 0;
while (*ptr != '\0'){
if (*ptr == ' ')
{
num_spaces++;
}
ptr++;
}
//checkQuit(str);
checkNumSpaces = checkSpaces(num_spaces);
}
int tempLen = strlen(str);
while (tempLen > 21){
printf("ERROR! Input string too long. \n");
ptr = str;
scanf("> %65[^\n]%*c", str);
str[strlen(str)+1] = '\0';
tempLen = strlen(str);
num_spaces = 0;
while (*ptr != '\0'){
if (*ptr == ' ')
{
num_spaces++;
}
ptr++;
}
//checkQuit(str);
checkNumSpaces = checkSpaces(num_spaces);
}
}
}while(checkNumSpaces <= 2);//end doWhile
int lenTemp = strlen(str);
printf("Length of string: %d\n", lenTemp);
tokens = (char**) malloc (sizeof(char*) * (num_spaces+1));
ptr = str;
while (*ptr != '\0'){
end_ptr = ptr;
num_chars = 0;
while (*end_ptr != ' ' && *end_ptr != '\0'){
num_chars++;
end_ptr++;
}
temp = *end_ptr;
*end_ptr = '\0';
tokens[num_tokens] = (char*) malloc(sizeof(char)*(num_chars+1));
strcpy( tokens[num_tokens], ptr);
num_tokens++;
*end_ptr = temp;
ptr = end_ptr+1;
}
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;
}
printf("%s \n",str);
for (int i=0; i < num_tokens; i++){
if (is_digit(tokens[i]) == 0 ){
printf("INT ");
}
else {
printf("STR ");
}
}
.
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?