473,748 Members | 2,211 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need to seperate input scanf()

ern
I'm using scanf("%s",user Input) to capture up to three words from the
user. I want to seperate those three words into three variables:

char * firstWord;
char * secondWord;
char * thirdWord;

Is there an easy way/function that can do this already? Thanks!

Nov 15 '05 #1
9 1977
ern wrote on 20/09/05 :
I'm using scanf("%s",user Input) to capture up to three words from the
user. I want to seperate those three words into three variables:

char * firstWord;
char * secondWord;
char * thirdWord;
These variables are just uninitialized pointers. If you insist in using
scanf(), you probably want a static or dynamic array of char.
Is there an easy way/function that can do this already? Thanks!


fgets() and a hand made parser using strchr(), strstr() etc.

Of course, there is a strtok() function that can be used to separate
tokens, but it has many caveats.

I think that POSIX.1 defines strtok_r() and strsep() that are better.
But they are not standard and probably not portable everywhere.

http://www.hmug.org/man/3/strtok_r.php
--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC
Nov 15 '05 #2
ern
Isn't fgets() for files? I want to read from STDIN.

Nov 15 '05 #3
ern wrote on 20/09/05 :
Isn't fgets() for files? I want to read from STDIN.


I guess you meant stdin. fgets() is for stream. Surprise, stdin *is* a
stream.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC
Nov 15 '05 #4
ern
thanks. fgets and strtoks work pretty good. one more thing... how can
I return an array of strings? I'd imagine the syntax would be
something like:

char *[ ] myFunction();

Nov 15 '05 #5
ern wrote on 20/09/05 :
thanks. fgets and strtoks work pretty good. one more thing... how can
I return an array of strings? I'd imagine the syntax would be
something like:

char *[ ] myFunction();


No. There is no way to return an array in C[1]. All you can do is to
return the address of the first element of some array. (but you neeed a
way to know the limit : size, sentinel...).

Note that the returned address must be valid after the leaving from the
function. Hence, addresses local to the callee (called ?) are
forbidden.

-----------------
[1] However, you can return a copy of a structure holding an array, but
it's ugly and and more seriously inefficient and even unsafe if the
size is big....

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair
Nov 15 '05 #6
I would like to know if this code snippet effectively allocates and
deallocates mem for the 2-D arr
char** retStrArr(void)
{
char** arr;
int i=0;
arr = (char**) malloc(NUM_OF_S TRINGS*sizeof(c har*));
for(i=0;i<NUM_O F_STRINGS;i++)
{
arr[i]=(char*) malloc(STR_LENG TH*sizeof(char) );
/* strcpy(arr[i],"abc"); */
}
return arr;
}

int main(void)
{
int i=0
char** arr=retStrArr() ;
for(i=0;i<NUM_O F_STRINGS;i++)
{
free(arr[i]);
}
free(arr);
}

Regards,
Mohan S N

Nov 15 '05 #7
Frodo Baggins wrote on 21/09/05 :
I would like to know if this code snippet effectively allocates and
deallocates mem for the 2-D arr

char** retStrArr(void)
{
char** arr;
int i=0;
arr = (char**) malloc(NUM_OF_S TRINGS*sizeof(c har*));
for(i=0;i<NUM_O F_STRINGS;i++)
{
arr[i]=(char*) malloc(STR_LENG TH*sizeof(char) );
/* strcpy(arr[i],"abc"); */
}
return arr;
}

int main(void)
{
int i=0
char** arr=retStrArr() ;
for(i=0;i<NUM_O F_STRINGS;i++)
{
free(arr[i]);
}
free(arr);
}


My compiler just told me that there is something wrong with your code :

main.c:8: warning: no previous prototype for 'retStrArr'
main.c: In function `retStrArr':
main.c:11: error: implicit declaration of function `malloc'
main.c:11: warning: nested extern declaration of `malloc'
<internal>:0: warning: redundant redeclaration of 'malloc'

main.c:11: error: `NUM_OF_STRINGS ' undeclared (first use in this
function)
main.c:11: error: (Each undeclared identifier is reported only once
main.c:11: error: for each function it appears in.)
main.c:14: error: `STR_LENGTH' undeclared (first use in this function)

main.c: In function `main_':

main.c:23: error: syntax error before "char"
main.c:24: error: `NUM_OF_STRINGS ' undeclared (first use in this
function)
main.c:26: error: implicit declaration of function `free'
main.c:26: warning: nested extern declaration of `free'
main.c:26: error: `arr' undeclared (first use in this function)
main.c:28: warning: nested extern declaration of `free'
main.c:26: warning: redundant redeclaration of 'free'
main.c:26: warning: previous implicit declaration of 'free' was here

Please provide a compiling code if you want an evaluation...

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC
Nov 15 '05 #8
(supersedes <mn************ ***********@YOU RBRAnoos.fr>)

Frodo Baggins wrote on 21/09/05 :
I would like to know if this code snippet effectively allocates and
deallocates mem for the 2-D arr

char** retStrArr(void)
{
char** arr;
int i=0;
arr = (char**) malloc(NUM_OF_S TRINGS*sizeof(c har*));
for(i=0;i<NUM_O F_STRINGS;i++)
{
arr[i]=(char*) malloc(STR_LENG TH*sizeof(char) );
/* strcpy(arr[i],"abc"); */
}
return arr;
}

int main(void)
{
int i=0
char** arr=retStrArr() ;
for(i=0;i<NUM_O F_STRINGS;i++)
{
free(arr[i]);
}
free(arr);
}


My compiler just told me that there is something wrong with your code :

main.c:8: warning: no previous prototype for 'retStrArr'
main.c: In function `retStrArr':
main.c:11: error: implicit declaration of function `malloc'
main.c:11: warning: nested extern declaration of `malloc'
<internal>:0: warning: redundant redeclaration of 'malloc'

main.c:11: error: `NUM_OF_STRINGS ' undeclared (first use in this
function)
main.c:11: error: (Each undeclared identifier is reported only once
main.c:11: error: for each function it appears in.)
main.c:14: error: `STR_LENGTH' undeclared (first use in this function)

main.c: In function `main_':

main.c:23: error: syntax error before "char"
main.c:24: error: `NUM_OF_STRINGS ' undeclared (first use in this
function)
main.c:26: error: implicit declaration of function `free'
main.c:26: warning: nested extern declaration of `free'
main.c:26: error: `arr' undeclared (first use in this function)
main.c:28: warning: nested extern declaration of `free'
main.c:26: warning: redundant redeclaration of 'free'
main.c:26: warning: previous implicit declaration of 'free' was here

Please provide a compiling code if you want an evaluation...

Once fixed, and secured, the code is fine :

#include <stdlib.h>

#define NUM_OF_STRINGS 4
#define STR_LENGTH 32

static char **retStrArr (void)
{
char **arr = malloc (NUM_OF_STRINGS * sizeof *arr);

if (arr != NULL)
{
int i = 0;

for (i = 0; i < NUM_OF_STRINGS; i++)
{
arr[i] = malloc (STR_LENGTH * sizeof *arr[i]);
sprintf (arr[i], "abc%d", i);
}
}
return arr;
}

int main (void)
{
char **arr = retStrArr ();

if (arr != NULL)
{
int i = 0;
for (i = 0; i < NUM_OF_STRINGS; i++)
{
printf ("%s\n", arr[i]);
free (arr[i]);
}
free (arr);
}
return 0;
}

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"There are 10 types of people in the world today;
those that understand binary, and those that dont."
Nov 15 '05 #9
On 21 Sep 2005 10:09:32 -0700, "Frodo Baggins" <fr*********@gm ail.com>
wrote:
I would like to know if this code snippet effectively allocates and
deallocates mem for the 2-D arr
char** retStrArr(void)
{
char** arr;
int i=0;
arr = (char**) malloc(NUM_OF_S TRINGS*sizeof(c har*));
You did specify effective.

Don't cast the return from malloc. The only thing it does is
prevent the compiler from warning you about undefined behavior if you
forget to include a prototype for malloc.

Check the return from malloc. You need to know if it succeeded.
for(i=0;i<NUM_O F_STRINGS;i++)
{
arr[i]=(char*) malloc(STR_LENG TH*sizeof(char) );
Doyouenjoyreadi nglongsentences withnospaces?

sizeof(char) will always be 1.
/* strcpy(arr[i],"abc"); */
}
return arr;
}

int main(void)
{
int i=0
char** arr=retStrArr() ;
You need to check the return from the function to determine if it
succeeded.
for(i=0;i<NUM_O F_STRINGS;i++)
{
free(arr[i]);
}
free(arr);
}

<<Remove the del for email>>
Nov 15 '05 #10

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

Similar topics

4
7987
by: Intaek LIM | last post by:
Hello. I always used cin in C++ for standard input. But, with C, I must use scanf. Integers, chars are all fine with scanf. The problem is... I cannot read floating point value like 'double' with scanf. ----------------------- double d;
3
1309
by: Sathyaish | last post by:
Towards the end of this thread here http://www.codeguru.com/forum/showthread.php?t=293945 a poster named cma said that if we wanted to ignore the input in the getchar() function, we could place a call to scanf just before the getchar in this fashion and the input recieved from the getchar will be ignored (only the next one character): int temp;
6
2286
by: Kobu | last post by:
Do the "larger" input functions like scanf, gets, fgets use fgetc to take input or an operating system call function like read() (I know it could be any "way", but I'm trying to find out how it's best to "think of it")? I've seen some explain it as if they call fgetc internally, then I've seen some people explain it as if they call some lower level OS system call like read(). I've even seen some older posts talk about a input functions...
7
5638
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store strings of any lengths into an array of pointers to char type variable. my problem is: given the declaration
17
4817
by: Martin Jørgensen | last post by:
Hi, Since I'm a newbie I have some small but quick (probably) stupid questions also :-) This is my "get_double" function which takes a default argument also of type double. The function returns a value of type double so I can write something like value = getdouble(0.5); in my program. --------------
18
5098
by: pipito | last post by:
Hi...i am a beginner in C programming... my question is like this... im using the scanf in C to accept input data in output area, printf("name: ");scanf("%s",name); printf(Address: ");scanf("%s",address); printf("age: ");scanf("%d",age); when i run the program, i use a spacebar in the input data, the following string after i press the space bar doesnt read anymore or it
4
2802
by: sandvet03 | last post by:
I am trying to expand on a earlier program for counting subs and now i am trying to replace substrings within a given string. For example if the main string was "The cat in the hat" i am trying to find a chosen substring lets say "cat" and then replace it with a difrent inputed substring say "dog". Tried to get as far as i could on my own but need some help, sugestions, snippets or guidence. # include<stdio.h> # include<math.h> #...
13
4371
by: FerrisUML | last post by:
Hello everyone! I new to C and am having the following problem. In the below program, the last scanf is being ignored and the program exits. Can anyone see anything that im doing wrong? Thanks in advance. #include <stdio.h> /* HOMEWORK: Assignment 1 Name: Dennis McQuilken
1
2787
by: rockchicx23 | last post by:
i have to write a program that is a guessing the number game. the user has to choose the number of games they want to play. i need help setting up the loop that will run the number of times the user wants it to here is my code so far //Assignment 2 Play //In this guessing game the user will be asked to guess a number from between 1-100 //The user has ten tries if they donot guess the right number its game over //The user also gets to...
0
8991
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
8831
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
9552
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
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8245
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
6796
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
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4877
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
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

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.