[英]One line is being skipped in file with isalpha()
I am using isalpha() to determine if there are characters on the line and it is showing that the line "90 1 0" contains alphabetic characters. 我正在使用isalpha()确定行上是否有字符,并显示“ 90 1 0”行包含字母字符。
Here is the relevant code 这是相关的代码
bool digitTest(char *test, int arysize)
{
int i;
for (i =0; i<arysize; i++)
{
if ((isalpha(test[i])) != 0){
return 0;
}
if (i==arysize)
return 1;
i++;
}
return 1;
}
It is called here 叫这里
char buffer[4096] = {};
while(NULL!=fgets(buffer, sizeof(buffer), fp)){
if (digitTest(buffer, 4096) == 0){
printf ("contains alpha\n");
continue;
/*printing code if there is no alphabetic characters below, i do not believe it is relevant*/
and this is output 这是输出
1
1
1
contains alpha
contains alpha
contains alpha
25123.90
54321.23
6
and input 和输入
1
1
1
89 23.5 not a number
90 1 0
-5.25 not a number 10000
25123.90 54321.23 6
The code has a few problems: 该代码有一些问题:
You shouldn't check all buffer. 您不应该检查所有缓冲区。 Check buffer until
\\0
. 检查缓冲区,直到
\\0
为止。 because the output of fgets
is a C-style string. 因为
fgets
的输出是C样式的字符串。
Second problem is an extra i++
in function digitTest
. 第二个问题是在
digitTest
函数中有一个额外的i++
。 You should remove it. 您应该删除它。
You don't need arysize
any more. 您不再需要
arysize
。
Use this digitTest
function instead 使用此
digitTest
函数代替
int digitTest(char *test)
{
int i;
for (i=0; test[i] && test[i] != '\n'; i++)
{
if (isalpha(test[i]) != 0)
return 0;
}
return 1;
}
(maybe has minor bugs, I didn't test it) (也许有一些小错误,我没有测试过)
And call it like this: 并这样称呼它:
while( fgets(buffer, sizeof(buffer), fp) ) {
if (!digitTest(buffer)) {
printf ("contains alpha\n");
continue;
}
}
It Looks like you might be accessing locations in memory that contain characters, Change your code to 看来您可能正在访问包含字符的内存中的位置,将代码更改为
char buffer[4096] = {};
memset(buffer, 0, 4096);
while(NULL!=fgets(buffer, sizeof(buffer), fp)){
if (digitTest(buffer, strlen(buffer)) == 0){ //get actual length of buffer
printf ("contains alpha\n");
continue;
EDIT 编辑
In order to make your code not respond to either \\n
or \\r
do 为了使您的代码不响应
\\n
或\\r
bool digitTest(char *test, int arysize)
{
int i;
for (i =0; i<arysize; i++)
{
if( test[i] == '\r' || test[i] == '\n')
return 1;
if ((isalpha(test[i])) != 0){
return 0;
}
if (i==arysize)
return 1;
}
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.