473,383 Members | 1,925 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,383 software developers and data experts.

Very very very basic question

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

char input_string[50];

printf("Please enter conversion: ");
scanf("%s", input_string);

printf("The output is %s\n", input_string);

exit(0);
}
Why does this code ignore any input text after a space?

e.g. If I enter "Hello World" it only stores (and prints) "Hello" in
input_string.

Sorry for the stupid question, it's my first C program. :)
Nov 14 '05 #1
14 1521
in comp.lang.c i read:
scanf("%s", input_string); Why does this code ignore any input text after a space?


because that's what it's supposed to do:

s Matches a sequence of bytes that are not white-space characters.

--
a signature
Nov 14 '05 #2
"those who know me have no need of my name" <no****************@usa.net>
wrote in message news:m1*************@usa.net...
in comp.lang.c i read:
scanf("%s", input_string);

Why does this code ignore any input text after a space?


because that's what it's supposed to do:

s Matches a sequence of bytes that are not white-space characters.


Thanks.

What's the function I'm looking for then to take in any length of string
(whether white space or not)?
Nov 14 '05 #3
Peter wrote:
char input_string[50];

printf("Please enter conversion: ");
scanf("%s", input_string); Why does this code ignore any input text after a space?

e.g. If I enter "Hello World" it only stores (and prints) "Hello" in
input_string.


Using %s in scanf() will read characters up until it hits any whitespace
character. If you want to read a whole line including spaces, use fgets():

fgets(input_string, sizeof input_string, stdin);

Mind that fgets() will leave the \n on the end, assuming there is one.

--John
Nov 14 '05 #4
Using GNU libc, 'getline()' is a best choice (IMHO).

Another way is 'scanf' with the next pattern:

scanf("%[^\n\r]", input_string);

i.e "everything before newline or carriage return symbol". Beware of
buffer overflow ;)

Peter wrote:
"those who know me have no need of my name" <no****************@usa.net>
wrote in message news:m1*************@usa.net...
in comp.lang.c i read:

scanf("%s", input_string);


What's the function I'm looking for then to take in any length of string
(whether white space or not)?


Nov 14 '05 #5
Peter <pe**@hello.com> wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
You don't seem to need the last one here.
int main(void) {
char input_string[50];
printf("Please enter conversion: ");
You need here additionally

fflush( stdout );

to make sure that that string is printed out immediately. Strings
that don't end in a '\n' can stay in the internal output buffers
of the printf() function and only the fflush() makes sure it gets
written to the screen in this case.
scanf("%s", input_string);
printf("The output is %s\n", input_string);
exit(0);
A "return 0;" or "return EXIT_SUCCESS;" will do here perfectly well,
no reason to kill the program;-)
} Why does this code ignore any input text after a space?


Because scanf() always stops at spaces when reading in a string
(unless you tell it otherwise), assuming that that's the end of
the input string. The way to tell scanf() not to stop at spaces
is using

scanf("%[^\n]", input_string);

The "%[^\n]" tells scanf() only to stop on a newline character. But
than you still have a potential problem: if the user enters more
than 49 characters scanf() will happily write them past the end of
your 'input_string' array and then in principle everything can
happen (it may even seem to work). So you better make that

scanf("%49[^\n]", input_string);

to tell scanf() to accept not more than the 49 characters fitting
into the buffer (don't forget about the trailing '\0' that's needed
at the end of the string).

Since you seem to want to read a simple line it should be a lot
simpler to use fgets() here instead of scanf() (and never, ever
use gets(), it's horribly broken!). scanf() is rather difficult
to use correctly for reading user input and typically it's a lot
easier to simply read in a whole line with fgets() and then to
take that apart as necessary. That's also true if you e.g. want
an integer as input from the user - if the user types in some-
thing else it's difficult to catch that correctly with scanf()
and way much easier to deal with if you have the whole line and
can analyze it carefully. It's rumored that there are only very
few people who got the hang of using scanf() to savely read in
user input;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #6
Dmitry wrote:

Please don't top post. Replies belong after or interleaved with the text
you are replying to.
Using GNU libc, 'getline()' is a best choice (IMHO).
Not round here it isn't. Here we deal with standard C, not
implementation specific extensions. After all (or any of), what makes
you think the all the platforms the OP wants to use this on have GNU
libc? Especially since the post was from a Windows machine?
Another way is 'scanf' with the next pattern:

scanf("%[^\n\r]", input_string);

i.e "everything before newline or carriage return symbol". Beware of
buffer overflow ;)
Nor accurate would be don't do that ever. You should *never* read a
string from stdin without limiting the length. Also, fgets is designed
to do what the OP wants, i.e. read a line of text.
Peter wrote:
"those who know me have no need of my name"
<no****************@usa.net> wrote in message
news:m1*************@usa.net...
in comp.lang.c i read:
scanf("%s", input_string);

What's the function I'm looking for then to take in any length of
string (whether white space or not)?


Look up fgets in your C reference, and if you don't have one buy a copy
of K&~R2. Also read the comp.lang.c FAQ which you can find easily enough
with Google.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #7
Flash Gordon wrote:
Peter wrote:
.... snip ...

What's the function I'm looking for then to take in any length
of string (whether white space or not)?


Look up fgets in your C reference, and if you don't have one buy
a copy of K&~R2. Also read the comp.lang.c FAQ which you can find
easily enough with Google.


The OP can also download and use the freely available ggets
routine, written in purely standard C, which avoids most of the
nuisances involved with fgets and the insecurities of gets.

<http://cbfalconer.home.att.net/download/ggets.zip>

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #8
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Look up fgets in your C reference, and if you don't have one buy a
copy of K&~R2. Also read the comp.lang.c FAQ which you can find easily
enough with Google.


Surely Mr. Ritchie deserves to be complimented, not complemented.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9
Je***********@physik.fu-berlin.de writes:
[...]
scanf("%s", input_string);
printf("The output is %s\n", input_string);
exit(0);


A "return 0;" or "return EXIT_SUCCESS;" will do here perfectly well,
no reason to kill the program;-)


Within main(), "return 0;" and "exit(0);" are very nearly identical.
I tend to prefer return, but there's nothing wrong with using exit().

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #10
Keith Thompson <ks***@mib.org> writes:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Look up fgets in your C reference, and if you don't have one buy a
copy of K&~R2. Also read the comp.lang.c FAQ which you can find easily
enough with Google.


Surely Mr. Ritchie deserves to be complimented, not complemented.


K&++R2?
Nov 14 '05 #11

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
Keith Thompson <ks***@mib.org> writes:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Look up fgets in your C reference, and if you don't have one buy a
copy of K&~R2. Also read the comp.lang.c FAQ which you can find easily
enough with Google.


Surely Mr. Ritchie deserves to be complimented, not complemented.


K&++R2?

K&R2D2?
Nov 14 '05 #12
On Wed, 09 Feb 2005 05:37:02 GMT, Keith Thompson
<ks***@mib.org> wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Look up fgets in your C reference, and if you don't have one buy a
copy of K&~R2. Also read the comp.lang.c FAQ which you can find easily
enough with Google.


Surely Mr. Ritchie deserves to be complimented, not complemented.


Ooh, nice wordplay! Although I keep reading K&R2 as K2R2 and thinking
it's a robot...

Chris C
Nov 14 '05 #13
Keith Thompson wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
Look up fgets in your C reference, and if you don't have one buy a
copy of K&~R2. Also read the comp.lang.c FAQ which you can find easily
enough with Google.

Surely Mr. Ritchie deserves to be complimented, not complemented.

Yes, he has already been complemented by Mr. Kernighan.
Nov 14 '05 #14
On Tue, 8 Feb 2005 21:52:32 +0100, "Peter" <pe**@hello.com> wrote:
<snip>
What's the function I'm looking for then to take in any length of string
(whether white space or not)?

Others have already answered what you probably meant to ask, which is
how to input (up to) a line of data possibly containing space, or
perhaps "linear whitespace" or "horizontal whitespace" which includes
tab also. However, the definition of whitespace in C, and also in
(most?) Internet standards, includes newline, and CR and VT and FF. So
your question as stated is actually to read an entire (text) file into
memory -- or an entire TCP (e.g. HTTP) datastream, if on a system
where sockets are interchangeable with files (i.e. Unix) or otherwise
supported by stdio. If that's what you want, the simplest way is just

char buf [BIGENUF];
size_t len;
len = fread (buf, 1, sizeof buf /* or BIGENUF */, fp_eg_stdin);
/* if you want to use the result as a string in C: */
/* do the read for (sizeof buf) -1 (parens not required
but shown for clarity) aka BIGENUF -1 and then */
buf [len] = '\0' /* or just 0 */

If you can't determine in advance (at compile time, or in C99 or GCC
for a local=automatic buffer at declaration which must be before the
read) a buffer size that will be sufficiently large, you must either:

- determine file size, which can't be done fully portably, FAQ 19.12
at the usual places and http://www.eskimo.com/~scs/C-faq/top.html ,
then malloc that much space, checking for failure (return == NULL) and
handling as appropriate, otherwise read the data

- or, malloc a buffer of some "normal" size and try reading that much,
and if that doesn't reach EOF, realloc to a larger size and read more
etc. until either you get it all or realloc fails (out of memory)

In both cases plus a byte for a null terminator if you want a string.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #15

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

Similar topics

9
by: Tom | last post by:
Hey all, I've been planning to get myself started with DocBook for quite some time now, so when I unexpectedly encountered a task for which DocBook might actually be very useful, I thought I'd...
30
by: Vla | last post by:
why did the designers of c++ think it would be more useful than it turned out to be?
5
by: Lee David | last post by:
I went to the sun site and downloaded what I hope is the development part of java. I downloaded JDK5 with Netbeans. I installed it and now have a folder in my program group "Netbeans". Is that...
10
by: Jason Curl | last post by:
Greetings, I have an array of 32 values. This makes it extremely fast to access elements in this array based on an index provided by a separate enum. This array is defined of type "unsigned long...
6
by: msnews.microsoft.com | last post by:
Hello All, I am very new to ASP.NET and I have a basic question. Can somebody please explain? I have an .aspx Web Page with a textbox control. When the Page initially loads I am calling a...
8
by: pamelafluente | last post by:
Hi, I would like to get some advice. I know enough vb.net on win apps, but I have never worked on web applications and asp.net. I would appreciate if you could indicate the most basic...
6
by: aghazalp | last post by:
hi guys, this would be the most basic question ever...I am not a programmer but I am trying to learn programming in python...I was reading John Zelle's text book and instructed me to make .py file...
17
by: blueapricot416 | last post by:
This is a very basic question -- but I can't find the answer after looking for 20 minutes. If you code something like: function set_It() { setTimeout('Request_Complete("apple", -72)',5000) }...
7
by: Bruno43 | last post by:
Hi I am trying to learn Visual Basic and I am getting everything for the most part, mainly because of my ability to read code like a book, but my question is what is the best way to Navigate through...
56
by: mdh | last post by:
As I begin to write more little programs without the help of the exercises, little things pop up that I need to understand more fully. Thus, below, and although this is not the exact code, the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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.