Crystal Crystal - 1 month ago 9
C Question

Reading characters from a stream up to whitespace using isspace in c

I'm trying to write a function that takes a stream as an argument and reads from that stream and reads in the contents of the file up to the first whitespace as defined by the isspace function, and then uses the strtok function to parse the string. I'm not sure how to start it though with which function to read a line and ignore the whitespace. I know fgetc and getc only read one character at a time, and looking up the fscanf reference, will that work? Or does that only find items in your stream according to the format specifiers %s? Thanks!

Answer

C Answer

The fscanf s conversion will match a sequence of non-white-space characters. The input string stops at white space (as defined by isspace) or at the maximum field width, whichever occurs first. Note that there must be enough space in the provided buffer or it may be overflowed by long input.

FILE *fp;
char cstr[128];

fp = fopen("test.txt", "r");

while (!feof(fp))
{    
    fscanf(fp, "%s", cstr);
    ...
}

Original C Answer

The fgets function will allow you to read in the file one line at a time, but you will still need to check each character with isspace.

Since isspace may include space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') in its check for white-space characters, your best bet may be to read one character at a time in a loop using the fgetc function. Note that if the integer value returned by fgetc() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.

FILE *fp;
int c;

fp = fopen("test.txt", "r");
while ((c = fgetc(fp)) != EOF)
{
    if (isspace(c))
    {
        ...
    }
    else
    {
        ...
    }
}

Original C++ Answer

The istream::getline method will allow you to read in one line at a time and optionally specify the delimiter (default is '/n').

Since isspace may include space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') in its check for white-space characters, your best bet may be to read one character at a time in a loop using the istream::get method.

char c;
string str;
ifstream file("test.txt",ios::in);
while (file.get(c)) 
{
    if (isspace((unsigned char)c))
    {
        ...
    }
    else
    {
        str.push_back(c);
    }

    file.peek();
    if (file.eof())
    {
        break;
    }
}

Note: Error checking was omitted from the all of the above code for simplicity.

Comments