how can i read from file line by line and check each line if it is an integer?
FILE *fp;
fp = fopen("users.txt", "r");
while(fscanf(fp, "%d", &IDRead)!=EOF)
{
enter code here
}
fclose(fp);
how can i read from file line by line and check each line if it is an integer?
FILE *fp;
fp = fopen("users.txt", "r");
while(fscanf(fp, "%d", &IDRead)!=EOF)
{
enter code here
}
fclose(fp);
You can use fgets()
to read a line and isdigit()
to check if each character in the string is a number.
First we can make an isnumber()
function that checks if each character in a string is a number. To handle negative numbers we can check that the first character is either a digit or '-'.
bool isnumber(char* str) {
int len = strlen(str);
if (len <= 0) {
return false;
}
// Check if first char is negative sign or digit
if (str[0] != '-' && !isidigit(str[0])) {
return false;
}
// Check that all remaining chars are digits
for (int i = 1; i < len; i++) {
if (!isdigit(str[i])) {
return false;
}
}
return true;
}
Our isnumber()
function assumes the string has no leading or trailing white space, and a string retrieved from fgets()
may have both. We'll need a function that strips whitespace from both ends of a string. You can read about how to do so in this answer.
Now we can use our isnumber()
function inside of a while loop to check each line in a file with fgets()
.
FILE *fp = fopen("users.txt", "r");
if(!fp) {
perror("Failed to open file");
return -1;
}
const int MAX = 256;
char line[MAX];
while (fgets(line, MAX, fp) != NULL) {
stripLeadingAndTrailingSpaces(line);
printf("%s\t", line);
if (isnumber(line)) {
printf("is a number\n");
}
else {
printf("is not a number\n");
}
}
fclose(fp);