【发布时间】:2018-03-04 15:44:35
【问题描述】:
我的程序对来自用户的输入字符串进行标记,并从这些标记中辨别它们是字符串还是整数(如果任何字母字符附加到数字,意味着它与任何数字相邻 - 它是然后将其视为字符串)。
因此,以下输入:“this is 1string 123 1”应输出STR STR STR INT INT。我所做的:获取输入字符串,继续对其进行标记/拆分(使用空格分隔符),然后遍历拆分标记(使用 for 循环)以查看拆分标记是否具有字母表中的任何字符(大写或小写)。
现在,最后一句话是问题所在。我有一个名为 foundChar 的布尔值。如果找到任何字母字符,那么我会将 foundChar 设置为 true。从那里,我会做一个简单的 if 检查,看看 foundChar == true。但是,现在当我输入一个字符串时,它会打印空白?我不确定我在 C 中使用布尔值的方式是否正确,或者在哪里准确指出这里出了什么问题。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// main
int main (void)
{
// declare our stuff for stuffs
char string[255];
char *tokenizedString;
const char delimiter[2] = " ";
char *pch;
bool found = false;
int truth = 0;
// prompt our user
do {
do {
printf (">");
fgets (string, 65, stdin);
} while (strlen (string) <= 0);
// remove it "\n" so it can terminate from newline input
pch = strstr (string, "\n");
strncpy (pch, "\0", 1);
// tokenize the input string
tokenizedString = strtok (string, delimiter);
while (tokenizedString != NULL) {
// check for any character in the token
// if found = true, then it's a string by our premade definition
for (int i = 0; i < strlen (tokenizedString); i++) {
if ((i >= 'a' && i <= 'z')
|| (i >= 'A' && i <= 'Z')) {
found = true;
}
}
// if we find a char in the string
if (found == true) {
printf ("STR ");
}
// if the token is a number
else if (isdigit (*tokenizedString))
printf ("INT ");
tokenizedString = strtok (NULL, delimiter);
// reset charFound to zero for our next token
found = false;
}
printf ("\n");
} while (!(strlen (string) == 0));
} // end of program
输出
./prog why are
_________(这里实际上没有打印,空白!STR STR 应该打印,下面的下一个字符串也一样!)
./prog you not printing output for string
_________(这里也没有打印,应该打印 STR STR STR STR STR STR)
./prog 123
INT
./prog 1st
INT
./prog nor printing the right stuff
期望的输出
./prog why are
STR STR
./prog you not printing output for string
STR STR STR STR STR STR
./prog 123
INT
./prog 1st
STR
./prog nor printing the right stuff
STR STR STR STR STR
【问题讨论】:
-
(i >= 'a' && i <= 'z')-->(tokenizedString[i] >= 'a' && tokenizedString[i] <= 'z') -
为什么要检查字母?我会做相反的事情。使用
isdigit()检查数字,并将未通过的任何内容视为字符串字符。 -
啊,谢谢,对不起。我没看到,看了好几个小时。
-
好吧,虽然它的复杂性很荒谬,但我当时认为这是一个绝妙的主意。
标签: c string if-statement input boolean