473,385 Members | 1,397 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

check if line is whitespace

What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);

Thanks
Sep 3 '08 #1
15 13670
puzzlecracker wrote:
What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);
const line[127];

doesn't mean anything in c++. Apart from that, if line is an array of
char, I'm pretty much sure that somebody with "puzzlecracker" as
nickname will be more than able to solve it ;)

Best wishes,

Zeppe

Sep 3 '08 #2
On Wed, 03 Sep 2008 10:21:58 -0700, puzzlecracker wrote:
What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);

Thanks
supposing you are trying to read some input lines of 127 char wide... I
also think that "const char line[127]" is mentioned...

Read with getline() and check if empty with empty() function of the
string class.

// string::empty
#include <iostream>
#include <string>
using namespace std;

int main ()
{
string content;
string line;
cout << "Please introduce a text. Enter an empty line to finish:\n";
do {
getline(cin,line);
content += line + '\n';
} while (!line.empty());
cout << "The text you introduced was:\n" << content;
return 0;
}

HTH,
Sep 3 '08 #3
On Wed, 03 Sep 2008 19:43:50 +0200, utab wrote:
On Wed, 03 Sep 2008 10:21:58 -0700, puzzlecracker wrote:
>What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);

Thanks

supposing you are trying to read some input lines of 127 char wide... I
also think that "const char line[127]" is mentioned...
Of course with getline const char ... is wrong.
Sep 3 '08 #4
On Sep 3, 2:21*pm, puzzlecracker <ironsel2...@gmail.comwrote:
What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);

Thanks
bool isLineSpaced(const char line[127])
{
int i = 0;
for(; i<127 && line[i++] == ' '; );
return i==127;
}
Sep 3 '08 #5
Guys, yeah, I wrote something similar to yours suggestions:

if( (line[strlen(line) -1] == '\n') )
line[strlen(line) -1] = '\0';

//ignore whitespace lines
unsigned int i;
for(i=0; line[i]!='\0' && isspace(line[i]);i++)
;
if(i==strlen(line))
continue;
Sep 3 '08 #6
On Wed, 03 Sep 2008 11:19:30 -0700, puzzlecracker wrote:
Guys, yeah, I wrote something similar to yours suggestions:

if( (line[strlen(line) -1] == '\n') )
line[strlen(line) -1] = '\0';

//ignore whitespace lines
unsigned int i;
for(i=0; line[i]!='\0' && isspace(line[i]);i++)
;
if(i==strlen(line))
continue
Why not use strings instead ;)
Sep 3 '08 #7
Sam
DarÃ*o writes:
On Sep 3, 2:21Â*pm, puzzlecracker <ironsel2...@gmail.comwrote:
>What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);

Thanks
bool isLineSpaced(const char line[127])
{
int i = 0;
for(; i<127 && line[i++] == ' '; );
return i==127;
}
That's C, not C++.

The C++ solution would be:

#include <algorithm>
#include <cctype>
#include <functional>
#include <vector>

bool isLineSpaced(const std::vector<char&line)
{
return std::find_if(line.begin(), line.end(),
std::not1(std::ptr_fun(isspace))) == line.end();
}

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAki/F9sACgkQx9p3GYHlUOLL+ACfUxNPWYuSKZTELduf9axhnayY
R3EAn23Fg75QBZhxxjh7wZBi4BRXIcnV
=wy3/
-----END PGP SIGNATURE-----

Sep 3 '08 #8
On Sep 3, 7:21 pm, puzzlecracker <ironsel2...@gmail.comwrote:
What is the quickest way to check that the following:
const line[127]; only contains whitespace, in which case to ignore it.
You mean std::string line, don't you. The above isn't a legal
C++ declaration.
something along these lines:
isspacedLine(line);
Well, the standard library already has direct support for this,
but it's interface isn't the most friendly. But something like
the following should do the trick:

bool
isOnlySpaces(
std::string const& line,
std::locale const& locale = std::locale() )
{
return std::use_facet< std::ctype< char ( locale )
.scan_not( std::ctype_base::space,
line.data(), line.data() + line.size() )
== line.data() + line.size() ;
}

(If you're forced to use arrays of char, instead of string, this
solution still works perfectly well.)

More generally, however, I tend to use regular expressions in
such cases. If the line matches "^[:space:]*$", ignore it.
With a good implementation of regular expressions (which uses a
DFA if the expression contains no extensions), this can be just
as fast as the above, if not faster. (Just make sure you only
construct the regular expression once, and not every time you
call the function.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Sep 4 '08 #9
On Sep 4, 1:03 am, Sam <s...@email-scan.comwrote:
Darío writes:
On Sep 3, 2:21 pm, puzzlecracker <ironsel2...@gmail.comwrote:
What is the quickest way to check that the following:
const line[127]; only contains whitespace, in which case to ignore it.
something along these lines:
isspacedLine(line);
bool isLineSpaced(const char line[127])
{
int i = 0;
for(; i<127 && line[i++] == ' '; );
return i==127;
}
That's C, not C++.
Well, it's also C++, albeit not idiomatic or good C++.
The C++ solution would be:
#include <algorithm>
#include <cctype>
The C++ solution would use <locale>, and not <cctype>:-). (With
subsequent changes in the code, of course.)
#include <functional>
#include <vector>
bool isLineSpaced(const std::vector<char&line)
{
return std::find_if(line.begin(), line.end(),
std::not1(std::ptr_fun(isspace))) == line..end();
}
Which is fine, except that it has undefined behavior. What you
probably meant was somthing like:

struct NotIsSpace
{
bool operator()( char ch ) const
{
return ! std::isspace(
static_cast< unsigned char >( ch ) ) ;
}
} ;

bool
isEmptyLine(
std::string const& line )
{
return std::find_if( line.begin(), line.end(), NotIsSpace() )
== line.end() ;
}

(You cannot call the version of isspace in <cctypewith a char
without risking undefined behavior.)

Still, a quick benchmark shows that something like:

myCtype.scan_not( std::ctype_base::space,
myData.data(),
myData.data() + myData.size() )
== myData.data() + myData.size() ;

, with myCtype initialized with "std::use_facet< std::ctype<
char ( std::locale()" is roughly five times faster (at least
on one system: g++ 4.1 under Linux on an Intel). And it's
certainly more idiotic^H^H^Hmatic with regards to C++.

(FWIW, using a full regular expression was only about three
times slower than your solution. And is a lot more powerful.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Sep 4 '08 #10
On 3 Sep, 18:21, puzzlecracker <ironsel2...@gmail.comwrote:
What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);
is a C solution any good?

#include <cstring>

bool isspacedLine (const char* line)
{
size_t i = strspn (line, " \t\f\n");
return line[i] = '\0';
}

--
Nick Keighley
Sep 4 '08 #11
James Kanze wrote:
[...]
More generally, however, I tend to use regular expressions in
such cases. If the line matches "^[:space:]*$", ignore it.
With a good implementation of regular expressions (which uses a
DFA if the expression contains no extensions), this can be just
as fast as the above, if not faster.
I see that you mention execution speed here and in other posts of this
thread. Since you aren't in the Premature-Optimization "school of
thought", I re-read the original post, and it says "quickest way". I
think that wasn't meant as "the way which executes fastest", though; I
get it as: "how do I avoid spending time implementing this?". And, of
course, the best solution is letting others, like you, implement it.

--
Gennaro Prota | name.surname yahoo.com
Breeze C++ (preview): <https://sourceforge.net/projects/breeze/>
Do you need expertise in C++? I'm available.
Sep 4 '08 #12
puzzlecracker wrote:
What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);
Do you use Boost?

boost::algorithm::all(line, boost::algorithm::is_space())

See http://www.boost.org/doc/libs/1_36_0...ring_algo.html
--
Christian Hackl
Sep 4 '08 #13
On Sep 4, 5:41 pm, Gennaro Prota <gennaro/pr...@yahoo.comwrote:
James Kanze wrote:
[...]
More generally, however, I tend to use regular expressions in
such cases. If the line matches "^[:space:]*$", ignore it.
With a good implementation of regular expressions (which uses a
DFA if the expression contains no extensions), this can be just
as fast as the above, if not faster.
I see that you mention execution speed here and in other posts
of this thread. Since you aren't in the Premature-Optimization
"school of thought", I re-read the original post, and it says
"quickest way". I think that wasn't meant as "the way which
executes fastest", though; I get it as: "how do I avoid
spending time implementing this?".
I suspect that that's wishful thinking on your part. That's
what it should mean, but most of the time, most programmers do
still use "quickest" to refer to execution time. Since the
issue of execution time was raised, I felt it necessary to
address it. The regular expression solution is by far the
simplest, and it's execution time is NOT necessarily too bad.

Of course, the regular expression class I use here is my own,
not that of Boost. The two are significantly different, being
designed from the start with different goals in mind. For most
general use, Boost's regular expression is better than mine, but
in this particular case: my regular expression class supports
the or'ing of multiple regular expressions, with different
return values. So you can write something like:

enum { emptyLine, sectionHeader, attrValuePair } ;
static RegularExpression const re =
RegularExpression( "[[:space:]]*$", emptyLine )
| RegularExpression( "\[.*\][[:space:]]*$", sectionHeader )
| RegularExpression( ".*=.*", attrValuePair ) ;
std::string line ;
while ( std::getline( source, line ) ) {
switch ( re.match( line.begin(), line.end() ).acceptCode ) {
case emptyLine :
break ;

case sectionHeader :
// ...
break ;

case attrValuePair :
// ...
break ;

default :
// process syntax error...
break ;
}

Of course, for the empty line, I'd probably use:
"[[:space:]]*(#.*)?$", to allow comments.

And a small warning: the version of RegularExpression doesn't
support the $ at the end to require a complete match, so you'd
have to add special code to handle this. I've recently reworked
the class considerably, however, for various reasons, and my
current version does have an option to require matching the
complete string, instead of just the start. It also supports
dumping the regular expression as a StaticRegularExpression, a
POD with static initialization that you then compile and link
into your program. (Not that the time to initialize the regular
expression would be an issue here, but I have some that are
complicated enough that parsing and initialing the expression
takes several minutes.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Sep 5 '08 #14
James Kanze wrote:
>I re-read the original post, and it says
"quickest way". I think that wasn't meant as "the way which
executes fastest", though; I get it as: "how do I avoid
spending time implementing this?".

I suspect that that's wishful thinking on your part.
I certainly couldn't wish that people made such requests. It was the
way I got it, given the OP precedents; a suspect, if you wish, like
your erroneous suspect that I was wishing that.

--
Gennaro Prota | name.surname yahoo.com
Breeze C++ (preview): <https://sourceforge.net/projects/breeze/>
Do you need expertise in C++? I'm available.
Sep 5 '08 #15
On Wed, 3 Sep 2008 10:21:58 -0700 (PDT), puzzlecracker <ir*********@gmail.comwrote:
What is the quickest way to check that the following:

const line[127]; only contains whitespace, in which case to ignore it.

something along these lines:

isspacedLine(line);
Reformulate your problem to use std::string, and then:

/**
* True iff s is empty or only contains space and/or TABs.
*/
bool util::isblank(const std::string& s)
{
return s.find_first_not_of(" \t")==std::string::npos;
}

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se R'lyeh wgah'nagl fhtagn!
Sep 8 '08 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Dwayne Epps | last post by:
I've created a function that checks form fields that only will have letters. This is the script: <script type="text/javascript" language="javascript"> function validateString(field, msg, min,...
1
by: Neil Morris | last post by:
Hi I have the following code that lists first names of people who's surnames are 'Morris'. What I am trying to do is search for first names that don't start at the beginning of the line ie. have...
5
by: Susan Sherpi | last post by:
Hi. Thanks to Eric Sosman for showing me what was wrong with my code in an earlier posting. He wrote, quoting me: >> I want to read a line of decimal integers from standard input into an >>...
1
by: C#User | last post by:
hi, I am using vs2000, I want to print the code out with the line number, how to do it? Thanks!
4
by: Laphan | last post by:
Hi all In my functions I'm using a double-check all the time to trap if a value has nothing in it and my question is do I need this double-check. My check line is: IF IsNull(xxx) OR...
8
by: nick | last post by:
i use sscanf()to get the words in a line, it will skip all the space automatically, if i want to know how many spaces were skipped and get the words in a line, what can i do? thanks!
1
by: David | last post by:
I have rows of 8 numerical values in a text file that I have to parse. Each value must occupy 10 spaces and can be either a decimal or an integer. // these are valid - each fit in a 10 character...
24
by: Ground21 | last post by:
Hello. How could I read the whole text file line after line from the end of file? (I want to ~copy~ file) I want to copy file in this way: file 1: a b
25
by: Peter Michaux | last post by:
Hi, I'm thinking about code minimization. I can think of a few places where whitespace matters a + ++b a++ + b a - --b a-- -b when a line ends without a semi-colon in which case the new...
4
by: Shug | last post by:
Hi, We're reformatting a lot of our project code using the excellent uncrustify beautifier. However, to gain confidence that it really is only changing whitespace (forget { } issues for just...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.