I was trying to discard invalid values, ie whitespaces
and characters
as I want to only parse double values.
My .txt
file looks like this...
1.45-1.46
-1.56
1.78-dead
-abc
1.34-2.45
1.56-9.01
Basically, I only want to store valid doubles, so the first line 1.45-1.46
, the fifth line 1.34-2.45
and the last line 1.56-9.01
are valid and the rest are invalid.
I have written some code, however it does not recognize the whitespace
or characters
. I am getting a ISO C++ forbids comparison between pointer and integer
error.
This is the code
char **marks;
marks = new char*[7]
for(int i=0; i<7; i++)
{
marks[i] = new char[64];
istreams.getline(marks[i], 64);
char *delims;
delims = strtok (marks[i]," -");
while (delims != NULL)
{
if(delims == '') // DOES NOT LIKE THIS, I WANT IT TO CHECK FOR WHITESPACE AND ALPHA CHARACTERS LIKE 'A', 'B', 'C'...
{
cout << "Invalid double" << endl;
}
else
{
cout << atof(delims);
delims = strtok (NULL, " ,.-");
}
}
}
Check out the functions
isalpha(int)
isspace(int)
You'll need to check each char individually by casting it to an int, though:
bool containsWhitespace(char const * c) {
char temp = *c;
if(temp != '\0') {
if( isspace(temp) )
return true;
} else {
return false;
}
return containsWhitespace(++c);
}
int main() {
if(containsWhitespace("ThisIsATest")) printf("First test failed.");
if(!containsWhitespace("This is a test")) printf("Second test failed.");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.