【发布时间】:2018-03-09 17:04:14
【问题描述】:
说明:
提示用户输入一个或两个标记,以空格分隔,最多输入 20 个字符。
- 如果用户在到达换行符之前提供了超过 20 个字符,则打印提供的错误消息。
- 如果令牌数量不正确,请打印相应的错误消息。
- 如果输入正确,则打印相应的令牌类型。
提示用户输入(并提供输出),直到用户提供单个 STR 令牌
quit(不区分大小写)。程序应该立即退出而不输出。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
bool isNumeric(char *str);
void tokenizer(char *token);
int main() {
char buff[20];
while (strcmp(buff, "quit") != 0) {
printf("> ");
scanf("%[^\n]s", buff);
if (sizeof(buff) - 1 < strlen(buff)) {
printf("Input string too long.\n");
exit(1);
}
char *token;
tokenizer(token = strtok(buff, " "));
}
printf("\n");
return 0;
}
bool isNumeric(char *str) {
while (*str != '\0') {
if (*str < '0' || *str > '9')
return false;
str++;
}
return true;
}
void tokenizer(char *token) {
int tokenCount = 0;
while (token != NULL) {
tokenCount++;
if (tokenCount > 2) {
printf("\rERROR! Incorrect number of tokens found.\n");
exit(1);
}
if (isNumeric(token)) {
printf("INT ");
} else {
printf("STR ");
}
token = strtok(NULL, " ");
}
}
OUTPUT:一个说 STR 的 Endless 程序。我需要有关循环条件的帮助。
【问题讨论】:
-
第一步
scanf("%[^\n]s", buff);-->fgets(buff, sizeof buff, stdin);第二步:strtok(NULL, " ");-->strtok(NULL, " \n");
标签: c string loops while-loop scanf