Any way to take a word as input from stdin ?

R

Richard Bos

Pilcrow said:
Is there at least an index to other similar solutions to general
problems? In comp.lang.perl.misc one often sees people scolded for not
using tested, robust solutions, rather than reinventing the wheel. CPAN
largely fills most peoples' needs. At the risk of making myself a
complete bore, I ask again: why doesn't the C community follow this
example?

Mainly because for many things C is used for, someone else's "almost
good enough" solution is _not_ good enough. In PERL, well... you're
having to deal with PERL already. That your string library (or rather,
someone else's string library) is slightly tentacular doesn't matter
much when you're already up to your knees in Cthulhuspawn.

Richard
 
A

arnuld

I answered that question already (see the above link).


If thats C's way of doing things. I have to admit, it is very messy :( . I
really can't find why it is better than:

std::vector<std::string> svec;
 
V

vippstar

If thats C's way of doing things. I have to admit, it is very messy :( . I
really can't find why it is better than:

std::vector<std::string> svec;

Well, for starters, because it does compile.
 
R

Richard

Richard Heathfield said:
Pilcrow said:


I wish you wouldn't. You have every right to say what you said. I wasn't
being "precious" about it - merely surprised! In fact, I'd be quite
curious to know more about *why* you have a lot of trouble reading my
code. Maybe there's something I can change to make it easier for you to
read without making it more difficult for myself and others.

Speaking for myself and knowingly only picking on style things:

I hate this move to putting braces on their own lines. Its a horrible
waste of vertical space and "3 levels" for one unit is not natural.

e.g

while(t--){
doSomething(t);
doSomething2(t);
}

is much preferable to

while(t--)
{
doSomething(t);
doSomething2(t);
}

The closing brace matches to the opening "while". Clean. Economical.

Also you adopt the non "standard" option of putting your values to
compare against on the left. While "clever" it does read as traditional
"English" and is not adopted widely elsewhere.

e.g

while( 0 == getValue(t))
doSomething(t);

is horrible. 0 is not the thing was are interested in manipulating or
looking at. the return from getValue(t) is. It is that we compare
against a benchmark figure - therefore

while(getValue(t)==0)
doSomething(t);

reads much better and is more traditional.

Yes, we could argue until the cows come home about it and it is purely
style. But I have tried to justify my traditional K&R preferences. At
least you do not seem to have adopted Falconer's horrific habit of
having conditional targets on the same line e.g

if(error(r))printf("I'm a pedantic nutter");
 
R

Richard

Well, for starters, because it does compile.

Minus 3 for being too late on your attempt to get promoted into the
c.l.c "reg" upper echelon. But that atttempt combined with your
"indeeds", your "Mr heathfields" and various nauseating attempts at
belittling nOObs should ensure at least a cushion at RHs feet in the
near future.

Hint : it was perfectly clear what arnuld meant. Pretending other
languages do not exist (especially one as rooted in C history as C++) in
this NG is simply pathetic.
 
A

arnuld

It seems you have misunderstood.

The question was: why doesn't C have this feature (the ability to read
arbitrarily long lines) already? My answer to that perfectly reasonable
question is quite simply that there are many ways to do this, and no one
of them stands out as being the universally "right" decision.

NO, I simply got it. You have discussed several ways of accomplishing task
but none of them fits properly, you have shows the pros and cons of each
very *clearly* and hence then on that you prove reasonably why we don't
have such function in Std. Lib. I think you are pretty much technical,
unbiased and right about it.

Here's one obvious problem with that: it won't compile. Here's another:
assuming it did, it doesn't appear to be a function, so it's hard to see
how it could read anything at all.


I know you are playing here ;), It won't compile because its from C++.

<OT>
If i have to use C then I have to use one of the options you have suggested
or do it in other language, but thats personal. I have posted the code on
comap.lang.c++ with title "sorting the input":

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/0488e58b666d0eb1#


The only problem i was having with C is, my mind was drifted away very
badly from the *thinking-in-problem* to *thinking-about-language-issues*
and hence my focus was lost. C++ saved that focus and IMVVHO, may be I
am not sure, C++ version will run as fast as C version. But I don't think
C++ is better than C, because there are cases where C++ will not fit,
like resource and memory constraint systems, where there is no library
available, then even when if you use C++ compiler, you will have to
learn and use the *C Way*. You can't do anything else.

But since thats personal, Why will I even use C++ at all. I will prefer
Common Lisp on my side and will avoid working on resource and memory
constraint systems. I think they disrupt and kill my ability to
thinking-in-problem. </OT>
 
V

vippstar

[replying to me]
Minus 3 for being too late on your attempt to get promoted into the
c.l.c "reg" upper echelon. But that atttempt combined with your
"indeeds", your "Mr heathfields" and various nauseating attempts at
belittling nOObs should ensure at least a cushion at RHs feet in the
near future.

I'm tired of this. I don't give a crap what Heathfield thinks of me.
I'm here to learn C and help others do the same, not to socialize.
 
A

arnuld

you must be using Google Groups, thats why I don't see your post. Anyway,
Richard is right. It won't compile (this is comp.lang.c )
 
V

vippstar

you must be using Google Groups, thats why I don't see your post. Anyway,
Richard is right. It won't compile (this is comp.lang.c )

Yes I do. There's better spam filters than just blocking a service...
I'm also right; I meant that the other way is better than the latter
because the former *does* compile. (unlike the latter that does not)
 
R

Richard

[replying to me]
Minus 3 for being too late on your attempt to get promoted into the
c.l.c "reg" upper echelon. But that atttempt combined with your
"indeeds", your "Mr heathfields" and various nauseating attempts at
belittling nOObs should ensure at least a cushion at RHs feet in the
near future.

I'm tired of this. I don't give a crap what Heathfield thinks of me.
I'm here to learn C and help others do the same, not to socialize.

Hmmmm. Indeed. It's "Mr Heathfield" to you.
 
R

Richard Bos

Pilcrow said:
This is poor advice for a beginner. Whilst strtok does have its uses, it
also has issues - traps for the unwary programmer. These derive from its
maintenance of significant state between calls, which makes it unsuitable

I understood that, and I am a 'beginner'. It is very adequately covered
in textbooks (see 'C in a Nutshell', ISBN 0-596-00697-7, page 440),
somewhat less so in K&R2. And I gave the questioner an example to help
him. My dissatisfaction with strtok() is that repeated separation
characters are treated as one, making it difficult to present the user
with an intuitively understandable interface. It is not usually a good
idea to equate ignorance and stupidity.[/QUOTE]

There is also the catch that strtok() scribbles over its parameter,
meaning that you cannot use it to tokenise either a string literal, or
data you want to keep. This is something that catches out a lot of less
well-informed newbies.

Richard
 
R

Richard Bos

arnuld said:
If thats C's way of doing things. I have to admit, it is very messy :( . I
really can't find why it is better than:

std::vector<std::string> svec;

Confucius, he says: "if you want C++, you know where to find it".

Richard
 
R

Richard

Confucius, he says: "if you want C++, you know where to find it".

Richard

If I were looking at designing solutions in C for such things then it
would be remiss of me NOT to look to see how C++ has done it in the
meantime. It could lead to a lot of time saving. Sure you can not use
the C++ syntax but things are never there for "no reason". And in that
context mentioning the way C++ does it here is clearly topical and
possibly useful to C library designers.
 
J

James Kuyper

arnuld said:
I searched the c.l.c archives provided by Google as Google Groups with
"word input" as the key words and did not come up with anything good.


C++ has std::string for taking a word as input from stdin.


Could you identify the std::string feature that implements this? I
couldn't find any use of the word "word" anywhere in section 21 of the
C++ standard, which describes std::string.
 
J

James Kuyper

Richard said:
Speaking for myself and knowingly only picking on style things:

I hate this move to putting braces on their own lines. Its a horrible
waste of vertical space and "3 levels" for one unit is not natural.

Vertical space is not in short supply. Personally, I handle that issue
the same way Richard Heathfield does. My reason is that it makes it
easier to identify and move block statements around when there's a set
of lines which is used for the block, and only that block, including the
delimiting curly brackets.
Also you adopt the non "standard" option of putting your values to
compare against on the left. While "clever" it does read as traditional
"English" and is not adopted widely elsewhere.

e.g

while( 0 == getValue(t))
doSomething(t);

I don't personally use this style, for reasons similar to yours.
However, are you aware of the reason why some people do this? When a
literal is the left operand of a comparison, rather than the right,
there is no danger of your code being silently compiled if you
accidentally type "=" instead of "==". I'll grant you that this doesn't
make any difference when the right operand is also something which could
not be the left operand of an assignment, such as a function call.
However, this kind of rule is much more effective when used
consistently, rather than always asking yourself "is it needed here?". I
tried this style, but found it very hard to break old habits; but I
would not criticize people for adopting it.
 
R

Richard

James Kuyper said:
Vertical space is not in short supply. Personally, I handle that issue
the same way Richard Heathfield does. My reason is that it makes it
easier to identify and move block statements around when there's a set
of lines which is used for the block, and only that block, including
the delimiting curly brackets.

Sounds very rare to me. This moving blocks around. And even so its one
key stroke away to realign etc. hardly worth adopting an entire new
layout to support. I have emacs set up that a single sequence collects
the entire scope into the clipboard anyway.
I don't personally use this style, for reasons similar to
yours. However, are you aware of the reason why some people do this?

Yes. Well, one reason. And its not the same as the other one (which I
knew too :-;).
When a literal is the left operand of a comparison, rather than the
right, there is no danger of your code being silently compiled if you
accidentally type "=" instead of "==". I'll grant you that this

Fabricated and blown out of all proportion IMO. What about protecting
against someone typing "a==0" instead of "a=0". or one of a million
other errors. Its a coding error. And 2 seconds testing or debugging
puts that right.
doesn't make any difference when the right operand is also something
which could not be the left operand of an assignment, such as a
function call. However, this kind of rule is much more effective when
used consistently, rather than always asking yourself "is it needed
here?". I tried this style, but found it very hard to break old
habits; but I would not criticize people for adopting it.

I would. The perceived benefits are more than offset by the non standard
"reading" of the code. In my opinion of course. I now expect the usual
sycophants to appear telling us how their productivity increased 30000%
when they adopted this notation ....

It's amusing that the people I know you use this "back to front" trend
are also some of the worst "team players" I have ever encountered and
tend to be jobs worth language lawyers than good, practical programmers
interested in contributing to a consistent and maintainable code base.
 
R

Richard

Richard Heathfield said:
(e-mail address removed) said:
[replying to me]
Minus 3 for being too late on your attempt to get promoted into the
c.l.c "reg" upper echelon. But that atttempt combined with your
"indeeds", your "Mr heathfields" and various nauseating attempts at
belittling nOObs should ensure at least a cushion at RHs feet in the
near future.

I'm tired of this.

Yes, it's tiresome. But he's an attention-seeker, like all trolls. If you
never, ever reply to him, maybe - just *may*be - he'll get bored and drift
away, and the average C understanding of the group will increase by a
small but significant amount.

Not if there is no one to challenge you and your humongous ego and
inflated head.
Neither should you. The best strategy is to give people every reason to
think highly of you whilst, at the same time, not worrying whether or not
they do.

Vippstar's contributions to nOObs are invariably poorly worded or wrong
and then followed up with a "yes, I made a mistake there I meant to say
......".

Only a complete fool would not have noticed his attempts to ingratiate
himself with you and your clique by parroting the "Mr heathfield" form
of address and the cringingly horrible use of "Indeed" to promote an
image of knowledge, seniority and peer acceptance.

It's a shame that decency and politeness can not be mixed with "learning
and helping" in too many cases here. To be social costs nothing.

So basically, stick it where the sun does not shine you obnoxious
arse
 
P

Pilcrow

Pilcrow said:


I wish you wouldn't. You have every right to say what you said. I wasn't
being "precious" about it - merely surprised! In fact, I'd be quite
curious to know more about *why* you have a lot of trouble reading my
code. Maybe there's something I can change to make it easier for you to
read without making it more difficult for myself and others.

It's just a matter of 'accent'. Just as it's easiest for me to
understand someone who speaks with a regional accent similar to mine
(I'm a native of Brooklyn), I understand easiest a coding style similar
to mine. I really shouldn't have brought it up.
 
C

CBFalconer

Richard said:
There is also the catch that strtok() scribbles over its
parameter, meaning that you cannot use it to tokenise either a
string literal, or data you want to keep. This is something that
catches out a lot of less well-informed newbies.

Try this:

/* ------- file tknsplit.c ----------*/
#include "tknsplit.h"

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
Revised 2006-06-13 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh) /* length tkn can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) src++;

while (*src && (tknchar != *src)) {
if (lgh) {
*tkn++ = *src;
--lgh;
}
src++;
}
if (*src && (tknchar == *src)) src++;
}
*tkn = '\0';
return src;
} /* tknsplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable tkn abbreviations */

/* ---------------- */

static void showtkn(int i, char *tok)
{
putchar(i + '1'); putchar(':');
puts(tok);
} /* showtkn */

/* ---------------- */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char tkn[ABRsize + 1];

puts(teststring);
t = s;
for (i = 0; i < 4; i++) {
t = tknsplit(t, ',', tkn, ABRsize);
showtkn(i, tkn);
}

puts("\nHow to detect 'no more tkns' while truncating");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ',', tkn, 3);
showtkn(i, tkn);
i++;
}

puts("\nUsing blanks as tkn delimiters");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ' ', tkn, ABRsize);
showtkn(i, tkn);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file tknsplit.c ----------*/


/* ------- file tknsplit.h ----------*/
#ifndef H_tknsplit_h
# define H_tknsplit_h

# ifdef __cplusplus
extern "C" {
# endif

#include <stddef.h>

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
revised 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh); /* length tkn can receive */
/* not including final '\0' */

# ifdef __cplusplus
}
# endif
#endif
/* ------- end file tknsplit.h ----------*/
 
A

arnuld

As you know, that definition is fine for your program; others might
have different requirements.

Incidentally, the phrase "letters, numbers, or anything" seems
redundant. I think that a more precise rendering of what you meant
would be:

A "word" is a non-empty contiguous sequence of characters other
than space, tab, or newline, preceded or followed either by a
space, tab, or newline or by the start or end of the input.
It would also be good to specify whether the input is a string, a line
of text, or an entire text file.

It's pretty much clear what your definition of a word is. It's still
not at all clear what a word is in general (and it can't be, since the
term is used inconsistently).


I think std::string in C++ defines what exactly *definition* of word is.
Look at my code and see how std::string works and perhaps we can settle on
some common and standard meaning word. I don't like to put C++ code in a C
group and I think I don't have any choice to define what a word is:


/* A program that will ask user for input and then will print them
* in an alphabetical order
*
* VERSION 1.1
*
*/


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void ask_input( std::vector<std::string>& );
void print_vector( const std::vector<std::string>& );

int main()
{
std::vector<std::string> svec;

ask_input( svec );
std::sort( svec.begin(), svec.end() );
std::cout << "--------------------------------"
<< std::endl;
print_vector( svec );

return 0;
}



void ask_input( std::vector<std::string>& strvec )
{
std::string str;

while( std::cin >> str )
{
strvec.push_back( str );
}
}


void print_vector( const std::vector<std::string>& strvec )
{
std::vector<std::string>::const_iterator iter = strvec.begin();

for( ; iter != strvec.end(); ++iter )
{
std::cout << *iter << std::endl;
}
}


=================== OUTPUT =========================
[arnuld@dune ztest]$ g++ -ansi -pedantic -Wall -Wextra sort-input.cpp
[arnuld@dune ztest]$ ./a.out
and saurabh sumi smit sumit and arnuld
--------------------------------
and
and
arnuld
saurabh
smit
sumi
sumit
[arnuld@dune ztest]$


you see even if you put a line as input, std::string will automatically
dissect it into separate words.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top