i want to know how to check that a data is interger or not ? & how to check that the file is empty & how to get the dimensions of a matrix in a file by using pointers or arrays.
char str[10];
strcpy(str,"1.0")
n = sttlen(str)
int j = sscanf (str,"%d",&i);
if (n==j)
{
printf ("It is an integer");
}
else
{
printf ("It is not an integer");
}
>>>how to check that a data is interger or not ?
No matter what kind of data in the file, just read the file line by line to string,
then Use what i wrote on the below.
>>>how to check that the file is empty
look at the previous reply
>>>how to get the dimensions of a matrix in a file by using pointers or arrays
first of all you should read the data, otherwise, you can not know anything about the data, after you read the data, the count elements, then you get the dimention of martix
// Explanation
strcpy(str,"1.0"); // This is test data for str
n = sttlen(str) // getting lenth of the string
int j = sscanf (str,"%d",&i); // converting str (the buffer) to
// int If the buffer is integer value, then j
// must be equal to lenths
// otherwise buffer is not integer
// value
if (n==j)
{
printf ("It is an integer");
}
else
{
printf ("It is not an integer");
}
Forgot the semicolon, and you accidentally mistyped "strlen" as "sttlen". ^_^
For the integer bit, I don't understand how that would work since sscanf returns the number of items successfully read, not the number of characters...
char str[11], str2[11];
int i = 0;
size_t j = 0;
strcpy(str, "200");
memset(str2, 0, 11);
i = atoi(str);
if (i == 0) //atoi() returns a 0 value when it fails to convert the string
{
fputs("Could not convert the string to an integer.", stderr);
return -1;
}
j = sprintf(str2, "%d", i); //convert the int into a new string
//if (3 != 5), because sprintf() returns 3
// since strlen("200") is 3 and strlen("200.0") is 5
if (j != strlen(str))
printf("%s is not an integer.\n", str);
else
printf("%s is an integer.\n", str);
I think SteakRider is correct. "sscanf" returns the number of digits in the string. And if the number of digits are not equal to that of all the characters in the string, it means some other characters exist in the string, such as ".". In that case, the data represented by the string cannot be an integer.
>"sscanf" returns the number of digits in the string.
No, it doesn't. It returns the number of items successfully read from the string and stored in the specified variable(s):
1 2 3 4
char x[] = "11.0";
int i = 0;
int j = sscanf(x, "%d", &i);
printf("%d %d", i, j);
Output: 11 1
It returns the number of items successfully read from the string and stored in the variable(s) specified. If it reads 2 digits from the string "11.0" into a single integer, as it did in this example, then it returns the number of successful attempts, which in this case is 1. It doesn't return the number of digits that were successfully read.
This holds true for char arrays (C-style strings) as well: