473,748 Members | 10,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inputting strings.

What is the easiest way to take a string from a console while including
whitespaces? This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the length of each
line will vary at each use. Is there a way to get scanf to take a string
that contains whitespace? Or is there another function that would work?
-Thank you
Nov 13 '05 #1
8 4027
On Sat, 13 Sep 2003 02:56:37 -0500
"Kruton" <no*****@none.n o> wrote:
What is the easiest way to take a string from a console while including
whitespaces? This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the length of each
line will vary at each use. Is there a way to get scanf to take a string
that contains whitespace? Or is there another function that would work?
-Thank you


#include <stdio.h>
char buffer[bufsize];
fgets(buffer, bufsize, stdin);

Will read one line of text from standard input. Returns NULL on error or EOF, or
a pointer to the buffer on success.
Note that the newline is stored as well.

--
char*x(c,k,s)ch ar*k,*s;{if(!k) return*s-36?x(0,0,s+1):s ;if(s)if(*s)c=1 0+(c?(x(
c,k,0),x(c,k+=* s-c,s+1),*k):(x(* s,k,s+1),0));el se c=10;printf(&x( ~0,0,k)[c-~-
c+"1"[~c<-c]],c);}main(){x(0 ,"^[kXc6]dn_eaoh$%c","-34*1'.+(,03#;+, )/'///*");}
Nov 13 '05 #2
"Kruton" <no*****@none.n o> writes:
What is the easiest way to take a string from a console while including
whitespaces?


/* ******** ex ****** */
#include<stdio. h>

int main(void){
char buffer[200];
printf("Write the string : ");
fgets(buffer,20 0,stdin);
printf("The string you wrote was : %s",buffer);
return 0;
}
/* *************** *** */

bye.

Nov 13 '05 #3
Kruton wrote:

What is the easiest way to take a string from a
console while including whitespaces?
This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the
length of each line will vary at each use.
Is there a way to get scanf to take a string
that contains whitespace?


/* BEGIN new.c */

#include <stdio.h>

#define STRINGLENGTH 160
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
char string[STRINGLENGTH] = {0};
int rc;

fputs("Enter a string with spaces: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(STRINGLENG TH) "[^\n]%*[^\n]", string);
getchar();
if (rc > 0) {
printf("\nYour string is:\n\"%s\"\n", string);
}
return 0;
}

/* END new.c */
--
pete
Nov 13 '05 #4


pete wrote:
Kruton wrote:
What is the easiest way to take a string from a
console while including whitespaces?
This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the
length of each line will vary at each use.
Is there a way to get scanf to take a string
that contains whitespace?

/* BEGIN new.c */

#include <stdio.h>

#define STRINGLENGTH 160
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
char string[STRINGLENGTH] = {0};
int rc;

fputs("Enter a string with spaces: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(STRINGLENG TH) "[^\n]%*[^\n]", string);


STRINGLENGTH-1.
The array string is not large enough to accept 160 chars plus a
nul-terminating character. That would be 161.

getchar();
if (rc > 0) {
printf("\nYour string is:\n\"%s\"\n", string);
}
return 0;
}


--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #5
Al Bowers wrote:

pete wrote:
Kruton wrote:
What is the easiest way to take a string from a
console while including whitespaces?
This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the
length of each line will vary at each use.
Is there a way to get scanf to take a string
that contains whitespace?

/* BEGIN new.c */

#include <stdio.h>

#define STRINGLENGTH 160
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
char string[STRINGLENGTH] = {0};
int rc;

fputs("Enter a string with spaces: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(STRINGLENG TH) "[^\n]%*[^\n]", string);


STRINGLENGTH-1.
The array string is not large enough to accept 160 chars plus a
nul-terminating character. That would be 161.


Thank you.

I meant to write:

char string[STRINGLENGTH + 1] = {0};

since the length of a string,
is one less than the total number of bytes.

--
pete
Nov 13 '05 #6
"Nicola Mingotti" <ni************ *@libero.it> wrote:
#include<stdio. h>

int main(void){
char buffer[200];
printf("Write the string : ");
You need to add a flush here to ensure that the prompt appears on the
screen before the system starts waiting for input.
fflush(stdout);
fgets(buffer,20 0,stdin);
Magic number alert - very bad idea. Use
fgets(buffer, sizeof buffer, stdin);
That way you can change the buffer size in one place only.

You should also check whether the fgets returned a null pointer. If
so, it is undefined behaviour to try to print buffer.
printf("The string you wrote was : %s",buffer);
If the user typed a string longer than 199 characters there will be
no newline character stored at the end of the buffer, which means the
stdout stream may not be valid, as it is not terminated properly.
return 0;
}


--
Simon.
Nov 13 '05 #7
On Sat, 13 Sep 2003 07:56:37 UTC, "Kruton" <no*****@none.n o> wrote:
What is the easiest way to take a string from a console while including
whitespaces? This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the length of each
line will vary at each use. Is there a way to get scanf to take a string
that contains whitespace? Or is there another function that would work?


getc() or getchar() is what you're looking for.

If your parser is simple you will write it on your own, else you may
use yacc/bison as a parser generator. Both uses getc() to have direct
access to the stream to avoid dynamic buffers.

Get a char, check it against the ones you will accept in the state you
are currently and when needed change the state.

You can easy accept token after token without a buffer (except the
token itself requires some kind of). You can convert any numerical
value on the fly wheras you sees any error directly.

You can use fscanf() or other library functions only if you sure that
you have a trusted input. But trusted input is only possible when you
accepts only files written by a well tested program.

Ever when you have to read anything from stdin you are sure that your
input is really untrusted and brings anything wrong. But no library
function will be ready to read any possible wrong things.

Even gets() tends to buffer overflow!

It will be more easy to write a little parser that reads char by chare
and acts on it as to handle a buffer that may be always to short to
get anything:
- you awaits a maximum line lengh of 80: the input is 81 - buffer
overflow or extra handling to extend the buffer until you have a
complete line readed in
- you awaits a maximum line length of 132: ther are 32K without '\n'
waiting in the stream.
- You awaits 32K - but the stream has 2GB without '\n'

You can't never handle all possible errors with the higher level
standard library functions.

Using token tables, getc()/getchar() makes it quite easy to extend the
functionality of your program without rewriting anything when you have
to handle a new token or change the token parameters.

ungetc() is designed to put a single char back into the input stream -
but the character you puts back can be any charater - not only the one
you've readed last!

Even as ungetc() is designed to put a single character it is not too
hard to write a wrapper around gtc()/ungetc to stack more than one
back. Yes, you must then use only the wrapper to read - but macros are
your friends anyway.

At least getc() is in no ways slower than (f)gets(), scanf() or
whatever, because all of them use getc() internally.
As you have to tokenise the stream you will win some runtime when you
use getc() directly, because you saves the (formatted) copy from one
puffer to another and scan that new puffer again (multiple times). You
can bring each char ito its real destionation and format on the fly
instead.

O.k., you may have some extra overhead to handle states - but make a
well design before you starts coding and you gets more flexibility for
free - and you saves the overhead the higher leveld library brings
with:
- dynamic buffer only to get a complete line
malloc() is a source of errors you have to handle
- breaking the line into tokens by copying the data partially from the
input buffer into another buffer
temp (buffer) -> destination field or another temp to convert from
string to something else
- checking the results of the library functions to make something
strange to come around

--
Tschau/Bye
Herbert

eComStation 1.1 Deutsch Beta ist verügbar
Nov 13 '05 #8
"Kruton" <no*****@none.n o> wrote in message
news:pa******** *************** *****@none.no.. .
What is the easiest way to take a string from a console while including
whitespaces? This program's user will input a line of text that will
consist of multiple tokens, but the number tokens and the length of each
line will vary at each use. Is there a way to get scanf to take a string
that contains whitespace? Or is there another function that would work?
-Thank you


Well, the *easy* way is the gets(char[]) function to put text into an array,
but that has the minor disadvantage that if a user enters too long a string
you will overwrite your program's return value, which could leave you going
anywhere. A merely incompetent user might crash the kernel. A malicious one
could, in theory at least, execute arbitrary program code downloaded from
the internet.
If you're using gcc, there's a nice function called get_line() that will
automatically expand the string with malloc if someone enters a longer line.
Of course you have to create the char vector as dynamic memory, and this is
incompatiable with other compilers
Most people will use fgets(FILE*,cha r[],int), which reads input but won't go
outside the array. However, it makes you specify stdin each time and won't
delete the trailing \n.
If you know what you want it for, I'd recommend you write your own
getstring(char[],int) function, which lets you choose your own terminator
value, error messages etc. Here's mine as an example (with a few #defines
for you to customize)
#include <stdio.h>
#define TERMINATOR '\n'
#define SUCCESS 1
#define FAIL 0
//if you want to return the number of characters read
//#define CHARS
//if you want a printed error message when too much is entered
//#define MSG
int getstring(char* a, int len){
for(int i=0;;i++){
a[i]=getchar();
if(a[i]==TERMINATOR){
a[i]='\0';
#ifdef CHARS
return i;
#else
return SUCCESS
#endif
}
if(i==len){
a[i]='\0';//to give a proper string even though it won't contain
all the input
#ifdef MSG
fprintf(stderr, "Error: Invalid string: Too many characters before
TERMINATOR")
//replace TERMINATOR manually, probably with "ENTER"
#endif
return FAIL;
}
}
}


Nov 13 '05 #9

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

Similar topics

20
5772
by: Ravi | last post by:
Hi, I have about 200GB of data that I need to go through and extract the common first part of a line. Something like this. >>>a = "abcdefghijklmnopqrstuvwxyz" >>>b = "abcdefghijklmnopBHLHT" >>>c = extract(a,b) >>>print c "abcdefghijklmnop"
17
7398
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix...
10
2258
by: Randy Yates | last post by:
How to do? Such a simple #@%^&@ thing and I'm spending hours on it. For example, long mynum; istringstream mystr("380,900", istringstream::in); mystr >> mynum; cout << mynum;
3
1393
by: Aaron | last post by:
Hello, I'm getting this error. ASP/VB2005 A potentially dangerous Request.Form value was detected from the client (txtComments.... 1. Add a "Debug=true" directive at the top of the file that generated the error. Example:
0
1045
by: jasonwong | last post by:
Hi, I was wondering if anyone knows of a way to utilize the Runtime Parser to parse a text box filled with user input code. The user will be inputting HTML and data markup into a textbox that will represent their own customized control. Any suggestions would be greatly appreciated.
1
1194
by: yasin | last post by:
is it possible inputting characters from keyboard by codes.or can we use assemly interrupts in asp.net to press keyboard buttons by code.
0
1143
by: yasin | last post by:
is it possible inputting characters from keyboard by codes.or can we use assemly interrupts in asp.net to press keyboard buttons by code.
2
22605
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be read (the file will be written by only this program); file can be either in text or binary (preferably binary as the files may be read repeatedly); the amount and size of strings in the array won't be known until run time (in the example I have it in...
1
2548
by: Ramper | last post by:
Have a .txt document as: String int int int int int int int
2
1728
by: UofFprogrammer | last post by:
Hello, Several Weeks ago I asked a question about testing for the end of an input file. I have been using this method pretty well for inputting information from an external file. I am using C++. char line; while(file>>line){ Where line is a c-string and file is an input stream. But this only reads until the first space it encounters. I now want to try to take in an entire line, regardless of what it contains (such as whitespace) as a...
0
8984
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9530
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8237
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.