How do you allow spaces to be entered using scanf?
Using the following code:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.n", name);
A user can enter their name but when they enter a name with a space like Lucas Aardvark
, scanf()
just cuts off everything after Lucas
. How do I make scanf()
allow spaces
c string printf scanf whitespace
add a comment |
Using the following code:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.n", name);
A user can enter their name but when they enter a name with a space like Lucas Aardvark
, scanf()
just cuts off everything after Lucas
. How do I make scanf()
allow spaces
c string printf scanf whitespace
8
Note that more idiomatic is 'malloc(sizeof(char) * 256 + 1)', or 'malloc(256 + 1)', or even better (assuming 'name' will be used strictly locally) 'char name[256+1]'. The '+1' can act as a mneumonic for the null terminator, which needs to be included in the allocation.
– Barry Kelly
Aug 8 '09 at 4:47
@Barry - I suspectsizeof(char) + 256
was a typo.
– Chris Lutz
Jul 20 '11 at 22:06
add a comment |
Using the following code:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.n", name);
A user can enter their name but when they enter a name with a space like Lucas Aardvark
, scanf()
just cuts off everything after Lucas
. How do I make scanf()
allow spaces
c string printf scanf whitespace
Using the following code:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.n", name);
A user can enter their name but when they enter a name with a space like Lucas Aardvark
, scanf()
just cuts off everything after Lucas
. How do I make scanf()
allow spaces
c string printf scanf whitespace
c string printf scanf whitespace
edited Jun 17 '18 at 16:39
alk
58.7k763172
58.7k763172
asked Aug 8 '09 at 4:37
KrednsKredns
19.5k43140191
19.5k43140191
8
Note that more idiomatic is 'malloc(sizeof(char) * 256 + 1)', or 'malloc(256 + 1)', or even better (assuming 'name' will be used strictly locally) 'char name[256+1]'. The '+1' can act as a mneumonic for the null terminator, which needs to be included in the allocation.
– Barry Kelly
Aug 8 '09 at 4:47
@Barry - I suspectsizeof(char) + 256
was a typo.
– Chris Lutz
Jul 20 '11 at 22:06
add a comment |
8
Note that more idiomatic is 'malloc(sizeof(char) * 256 + 1)', or 'malloc(256 + 1)', or even better (assuming 'name' will be used strictly locally) 'char name[256+1]'. The '+1' can act as a mneumonic for the null terminator, which needs to be included in the allocation.
– Barry Kelly
Aug 8 '09 at 4:47
@Barry - I suspectsizeof(char) + 256
was a typo.
– Chris Lutz
Jul 20 '11 at 22:06
8
8
Note that more idiomatic is 'malloc(sizeof(char) * 256 + 1)', or 'malloc(256 + 1)', or even better (assuming 'name' will be used strictly locally) 'char name[256+1]'. The '+1' can act as a mneumonic for the null terminator, which needs to be included in the allocation.
– Barry Kelly
Aug 8 '09 at 4:47
Note that more idiomatic is 'malloc(sizeof(char) * 256 + 1)', or 'malloc(256 + 1)', or even better (assuming 'name' will be used strictly locally) 'char name[256+1]'. The '+1' can act as a mneumonic for the null terminator, which needs to be included in the allocation.
– Barry Kelly
Aug 8 '09 at 4:47
@Barry - I suspect
sizeof(char) + 256
was a typo.– Chris Lutz
Jul 20 '11 at 22:06
@Barry - I suspect
sizeof(char) + 256
was a typo.– Chris Lutz
Jul 20 '11 at 22:06
add a comment |
11 Answers
11
active
oldest
votes
People (and especially beginners) should never use scanf("%s")
or gets()
or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).
Remember than scanf
stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.
Use fgets()
(which has buffer overflow protection) to get your input into a string and sscanf()
to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf()
in this case anyway:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memoryn");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen (name) - 1] == 'n'))
name[strlen (name) - 1] = '';
/* Say hello. */
printf("Hello %s. Nice to meet you.n", name);
/* Free memory and exit. */
free (name);
return 0;
}
I didn't know aboutfgets()
. It actually looks easier to use thenscanf()
. +1
– Kredns
Aug 8 '09 at 6:37
7
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
4
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
add a comment |
Try
char str[11];
scanf("%10[0-9a-zA-Z ]", str);
Hope that helps.
7
I didn't even knowscanf()
accepted regex's! Thanks!!!!!
– Kredns
Aug 8 '09 at 4:41
55
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
1
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
7
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
2
why's there a trailings
in the format string?
– ajay
Jan 13 '14 at 14:13
|
show 4 more comments
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a 'n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv)
{
char name[20];
scanf("%[^n]s",name);
printf("%sn", name);
return 0;
}
1
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
3
As you know the buffer size, you can use%20[^n]s
to prevent buffer overflows
– osvein
Nov 11 '17 at 20:52
add a comment |
You can use this
char name[20];
scanf("%20[^n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^n]", variable);
}
char name[20];
getText("Your name", name, 20);
DEMO
1
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:scanf("%19[^n]", name);
(still +1 for the concise answer)
– Dr Beco
Jun 12 '15 at 1:12
1
Just as a side note,sizeof(char)
is by definition always 1, so there's no need to multiply by it.
– paxdiablo
Mar 22 '16 at 7:37
add a comment |
Don't use scanf()
to read strings without specifying a field width. You should also check the return values for errors:
#include <stdio.h>
#define NAME_MAX 80
#define NAME_MAX_S "80"
int main(void)
{
static char name[NAME_MAX + 1]; // + 1 because of null
if(scanf("%" NAME_MAX_S "[^n]", name) != 1)
{
fputs("io error or premature end of linen", stderr);
return 1;
}
printf("Hello %s. Nice to meet you.n", name);
}
Alternatively, use fgets()
:
#include <stdio.h>
#define NAME_MAX 80
int main(void)
{
static char name[NAME_MAX + 2]; // + 2 because of newline and null
if(!fgets(name, sizeof(name), stdin))
{
fputs("io errorn", stderr);
return 1;
}
// don't print newline
printf("Hello %.*s. Nice to meet you.n", strlen(name) - 1, name);
}
add a comment |
You can use the fgets()
function to read a string or use scanf("%[^n]s",name);
so string reading will terminate upon encountering a newline character.
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
add a comment |
getline()
Now part of POSIX, none-the-less.
It also takes care of the buffer allocation problem that you asked about earlier, though you have to take care of free
ing the memory.
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
1
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
add a comment |
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution.
If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^n]s",&name);
printf ("%sn",name);
2
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checkingerrno
and cleaning up the allocated memory as well.
– paxdiablo
Nov 10 '17 at 1:22
add a comment |
You may use scanf
for this purpose with a little trick. Actually, you should allow user input until user hits Enter (n
). This will consider every character, including space. Here is example:
int main()
{
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do
{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
} while (c != 'n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for
loop that takes char by char from input stream (till n
) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.
Hope this will help someone!
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
add a comment |
While you really shouldn't use scanf()
for this sort of thing, because there are much better calls such as gets()
or getline()
, it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == 'r' || c == 'n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: "%s"nn", s);
return 0;
}
There's a reason whygets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse thatscanf
because at least the latter has ways to make it safe.
– paxdiablo
Nov 10 '17 at 1:25
add a comment |
Use the following code to read string with spaces :
scanf("[%s/n]",str_ptr);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1247989%2fhow-do-you-allow-spaces-to-be-entered-using-scanf%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
People (and especially beginners) should never use scanf("%s")
or gets()
or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).
Remember than scanf
stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.
Use fgets()
(which has buffer overflow protection) to get your input into a string and sscanf()
to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf()
in this case anyway:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memoryn");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen (name) - 1] == 'n'))
name[strlen (name) - 1] = '';
/* Say hello. */
printf("Hello %s. Nice to meet you.n", name);
/* Free memory and exit. */
free (name);
return 0;
}
I didn't know aboutfgets()
. It actually looks easier to use thenscanf()
. +1
– Kredns
Aug 8 '09 at 6:37
7
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
4
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
add a comment |
People (and especially beginners) should never use scanf("%s")
or gets()
or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).
Remember than scanf
stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.
Use fgets()
(which has buffer overflow protection) to get your input into a string and sscanf()
to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf()
in this case anyway:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memoryn");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen (name) - 1] == 'n'))
name[strlen (name) - 1] = '';
/* Say hello. */
printf("Hello %s. Nice to meet you.n", name);
/* Free memory and exit. */
free (name);
return 0;
}
I didn't know aboutfgets()
. It actually looks easier to use thenscanf()
. +1
– Kredns
Aug 8 '09 at 6:37
7
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
4
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
add a comment |
People (and especially beginners) should never use scanf("%s")
or gets()
or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).
Remember than scanf
stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.
Use fgets()
(which has buffer overflow protection) to get your input into a string and sscanf()
to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf()
in this case anyway:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memoryn");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen (name) - 1] == 'n'))
name[strlen (name) - 1] = '';
/* Say hello. */
printf("Hello %s. Nice to meet you.n", name);
/* Free memory and exit. */
free (name);
return 0;
}
People (and especially beginners) should never use scanf("%s")
or gets()
or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).
Remember than scanf
stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.
Use fgets()
(which has buffer overflow protection) to get your input into a string and sscanf()
to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf()
in this case anyway:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memoryn");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen (name) - 1] == 'n'))
name[strlen (name) - 1] = '';
/* Say hello. */
printf("Hello %s. Nice to meet you.n", name);
/* Free memory and exit. */
free (name);
return 0;
}
edited Nov 10 '17 at 1:11
answered Aug 8 '09 at 4:59
paxdiablopaxdiablo
633k17012481670
633k17012481670
I didn't know aboutfgets()
. It actually looks easier to use thenscanf()
. +1
– Kredns
Aug 8 '09 at 6:37
7
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
4
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
add a comment |
I didn't know aboutfgets()
. It actually looks easier to use thenscanf()
. +1
– Kredns
Aug 8 '09 at 6:37
7
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
4
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
I didn't know about
fgets()
. It actually looks easier to use then scanf()
. +1– Kredns
Aug 8 '09 at 6:37
I didn't know about
fgets()
. It actually looks easier to use then scanf()
. +1– Kredns
Aug 8 '09 at 6:37
7
7
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
If you just want to get a line from the user, it is easier. It's also safer since you can avoid buffer overflows. The scanf family is really useful for turning a string into different things (like four chars and an int for example with "%c%c%c%c%d") but, even then, you should be using fgets and sscanf, not scanf, to avoid the possibility of buffer overflow.
– paxdiablo
Aug 8 '09 at 6:48
4
4
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
You can put maximum buffer size in scanf format, you just can't put runtime computed one without building the format at runtime (there isn't the equivalent of * for printf, * is a valid modificator for scanf with another behavior: suppressing assignation).
– AProgrammer
Aug 8 '09 at 11:55
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
Tell that to my professor.
– Jonathan Komar
Jun 10 '18 at 12:31
add a comment |
Try
char str[11];
scanf("%10[0-9a-zA-Z ]", str);
Hope that helps.
7
I didn't even knowscanf()
accepted regex's! Thanks!!!!!
– Kredns
Aug 8 '09 at 4:41
55
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
1
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
7
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
2
why's there a trailings
in the format string?
– ajay
Jan 13 '14 at 14:13
|
show 4 more comments
Try
char str[11];
scanf("%10[0-9a-zA-Z ]", str);
Hope that helps.
7
I didn't even knowscanf()
accepted regex's! Thanks!!!!!
– Kredns
Aug 8 '09 at 4:41
55
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
1
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
7
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
2
why's there a trailings
in the format string?
– ajay
Jan 13 '14 at 14:13
|
show 4 more comments
Try
char str[11];
scanf("%10[0-9a-zA-Z ]", str);
Hope that helps.
Try
char str[11];
scanf("%10[0-9a-zA-Z ]", str);
Hope that helps.
edited Jun 12 '15 at 1:56
Dr Beco
6,94353959
6,94353959
answered Aug 8 '09 at 4:39
Kelly GendronKelly Gendron
5,78453562
5,78453562
7
I didn't even knowscanf()
accepted regex's! Thanks!!!!!
– Kredns
Aug 8 '09 at 4:41
55
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
1
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
7
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
2
why's there a trailings
in the format string?
– ajay
Jan 13 '14 at 14:13
|
show 4 more comments
7
I didn't even knowscanf()
accepted regex's! Thanks!!!!!
– Kredns
Aug 8 '09 at 4:41
55
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
1
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
7
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
2
why's there a trailings
in the format string?
– ajay
Jan 13 '14 at 14:13
7
7
I didn't even know
scanf()
accepted regex's! Thanks!!!!!– Kredns
Aug 8 '09 at 4:41
I didn't even know
scanf()
accepted regex's! Thanks!!!!!– Kredns
Aug 8 '09 at 4:41
55
55
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
note, it doesn't do general regexes, just character classes
– rampion
Aug 8 '09 at 4:47
1
1
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
@rampion: Excellent side note (but still that's pretty cool).
– Kredns
Aug 8 '09 at 4:48
7
7
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
(1) Obviously to accept spaces, you need to put a space in the character class. (2) Note that the 10 is the maximum number of characters which will be read, so str has to point to a buffer of size 11 at least. (3) The final s here isn't a format directive but scanf will try here to match it exactly. The effect will be visible on an entry like 1234567890s where the s will be consumed but put no where. An other letter won't be consumed. If you put another format after the s, it will be read only if there is an s to be matched.
– AProgrammer
Aug 8 '09 at 11:52
2
2
why's there a trailing
s
in the format string?– ajay
Jan 13 '14 at 14:13
why's there a trailing
s
in the format string?– ajay
Jan 13 '14 at 14:13
|
show 4 more comments
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a 'n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv)
{
char name[20];
scanf("%[^n]s",name);
printf("%sn", name);
return 0;
}
1
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
3
As you know the buffer size, you can use%20[^n]s
to prevent buffer overflows
– osvein
Nov 11 '17 at 20:52
add a comment |
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a 'n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv)
{
char name[20];
scanf("%[^n]s",name);
printf("%sn", name);
return 0;
}
1
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
3
As you know the buffer size, you can use%20[^n]s
to prevent buffer overflows
– osvein
Nov 11 '17 at 20:52
add a comment |
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a 'n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv)
{
char name[20];
scanf("%[^n]s",name);
printf("%sn", name);
return 0;
}
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a 'n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv)
{
char name[20];
scanf("%[^n]s",name);
printf("%sn", name);
return 0;
}
answered Aug 9 '09 at 14:31
SVASVA
540146
540146
1
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
3
As you know the buffer size, you can use%20[^n]s
to prevent buffer overflows
– osvein
Nov 11 '17 at 20:52
add a comment |
1
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
3
As you know the buffer size, you can use%20[^n]s
to prevent buffer overflows
– osvein
Nov 11 '17 at 20:52
1
1
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
Careful with buffer overflows. If the user writes a "name" with 50 characters, the program will probably crash.
– brunoais
Jan 29 '13 at 15:17
3
3
As you know the buffer size, you can use
%20[^n]s
to prevent buffer overflows– osvein
Nov 11 '17 at 20:52
As you know the buffer size, you can use
%20[^n]s
to prevent buffer overflows– osvein
Nov 11 '17 at 20:52
add a comment |
You can use this
char name[20];
scanf("%20[^n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^n]", variable);
}
char name[20];
getText("Your name", name, 20);
DEMO
1
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:scanf("%19[^n]", name);
(still +1 for the concise answer)
– Dr Beco
Jun 12 '15 at 1:12
1
Just as a side note,sizeof(char)
is by definition always 1, so there's no need to multiply by it.
– paxdiablo
Mar 22 '16 at 7:37
add a comment |
You can use this
char name[20];
scanf("%20[^n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^n]", variable);
}
char name[20];
getText("Your name", name, 20);
DEMO
1
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:scanf("%19[^n]", name);
(still +1 for the concise answer)
– Dr Beco
Jun 12 '15 at 1:12
1
Just as a side note,sizeof(char)
is by definition always 1, so there's no need to multiply by it.
– paxdiablo
Mar 22 '16 at 7:37
add a comment |
You can use this
char name[20];
scanf("%20[^n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^n]", variable);
}
char name[20];
getText("Your name", name, 20);
DEMO
You can use this
char name[20];
scanf("%20[^n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^n]", variable);
}
char name[20];
getText("Your name", name, 20);
DEMO
edited Jun 21 '17 at 2:53
answered Aug 22 '13 at 3:24
Vitim.usVitim.us
9,87696280
9,87696280
1
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:scanf("%19[^n]", name);
(still +1 for the concise answer)
– Dr Beco
Jun 12 '15 at 1:12
1
Just as a side note,sizeof(char)
is by definition always 1, so there's no need to multiply by it.
– paxdiablo
Mar 22 '16 at 7:37
add a comment |
1
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:scanf("%19[^n]", name);
(still +1 for the concise answer)
– Dr Beco
Jun 12 '15 at 1:12
1
Just as a side note,sizeof(char)
is by definition always 1, so there's no need to multiply by it.
– paxdiablo
Mar 22 '16 at 7:37
1
1
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:
scanf("%19[^n]", name);
(still +1 for the concise answer)– Dr Beco
Jun 12 '15 at 1:12
I did not test, but based on other answers in this very page, I believe the correct buffer size for scanf in your example would be:
scanf("%19[^n]", name);
(still +1 for the concise answer)– Dr Beco
Jun 12 '15 at 1:12
1
1
Just as a side note,
sizeof(char)
is by definition always 1, so there's no need to multiply by it.– paxdiablo
Mar 22 '16 at 7:37
Just as a side note,
sizeof(char)
is by definition always 1, so there's no need to multiply by it.– paxdiablo
Mar 22 '16 at 7:37
add a comment |
Don't use scanf()
to read strings without specifying a field width. You should also check the return values for errors:
#include <stdio.h>
#define NAME_MAX 80
#define NAME_MAX_S "80"
int main(void)
{
static char name[NAME_MAX + 1]; // + 1 because of null
if(scanf("%" NAME_MAX_S "[^n]", name) != 1)
{
fputs("io error or premature end of linen", stderr);
return 1;
}
printf("Hello %s. Nice to meet you.n", name);
}
Alternatively, use fgets()
:
#include <stdio.h>
#define NAME_MAX 80
int main(void)
{
static char name[NAME_MAX + 2]; // + 2 because of newline and null
if(!fgets(name, sizeof(name), stdin))
{
fputs("io errorn", stderr);
return 1;
}
// don't print newline
printf("Hello %.*s. Nice to meet you.n", strlen(name) - 1, name);
}
add a comment |
Don't use scanf()
to read strings without specifying a field width. You should also check the return values for errors:
#include <stdio.h>
#define NAME_MAX 80
#define NAME_MAX_S "80"
int main(void)
{
static char name[NAME_MAX + 1]; // + 1 because of null
if(scanf("%" NAME_MAX_S "[^n]", name) != 1)
{
fputs("io error or premature end of linen", stderr);
return 1;
}
printf("Hello %s. Nice to meet you.n", name);
}
Alternatively, use fgets()
:
#include <stdio.h>
#define NAME_MAX 80
int main(void)
{
static char name[NAME_MAX + 2]; // + 2 because of newline and null
if(!fgets(name, sizeof(name), stdin))
{
fputs("io errorn", stderr);
return 1;
}
// don't print newline
printf("Hello %.*s. Nice to meet you.n", strlen(name) - 1, name);
}
add a comment |
Don't use scanf()
to read strings without specifying a field width. You should also check the return values for errors:
#include <stdio.h>
#define NAME_MAX 80
#define NAME_MAX_S "80"
int main(void)
{
static char name[NAME_MAX + 1]; // + 1 because of null
if(scanf("%" NAME_MAX_S "[^n]", name) != 1)
{
fputs("io error or premature end of linen", stderr);
return 1;
}
printf("Hello %s. Nice to meet you.n", name);
}
Alternatively, use fgets()
:
#include <stdio.h>
#define NAME_MAX 80
int main(void)
{
static char name[NAME_MAX + 2]; // + 2 because of newline and null
if(!fgets(name, sizeof(name), stdin))
{
fputs("io errorn", stderr);
return 1;
}
// don't print newline
printf("Hello %.*s. Nice to meet you.n", strlen(name) - 1, name);
}
Don't use scanf()
to read strings without specifying a field width. You should also check the return values for errors:
#include <stdio.h>
#define NAME_MAX 80
#define NAME_MAX_S "80"
int main(void)
{
static char name[NAME_MAX + 1]; // + 1 because of null
if(scanf("%" NAME_MAX_S "[^n]", name) != 1)
{
fputs("io error or premature end of linen", stderr);
return 1;
}
printf("Hello %s. Nice to meet you.n", name);
}
Alternatively, use fgets()
:
#include <stdio.h>
#define NAME_MAX 80
int main(void)
{
static char name[NAME_MAX + 2]; // + 2 because of newline and null
if(!fgets(name, sizeof(name), stdin))
{
fputs("io errorn", stderr);
return 1;
}
// don't print newline
printf("Hello %.*s. Nice to meet you.n", strlen(name) - 1, name);
}
answered Aug 8 '09 at 16:04
ChristophChristoph
129k31156214
129k31156214
add a comment |
add a comment |
You can use the fgets()
function to read a string or use scanf("%[^n]s",name);
so string reading will terminate upon encountering a newline character.
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
add a comment |
You can use the fgets()
function to read a string or use scanf("%[^n]s",name);
so string reading will terminate upon encountering a newline character.
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
add a comment |
You can use the fgets()
function to read a string or use scanf("%[^n]s",name);
so string reading will terminate upon encountering a newline character.
You can use the fgets()
function to read a string or use scanf("%[^n]s",name);
so string reading will terminate upon encountering a newline character.
edited Sep 17 '12 at 12:31
jonsca
8,631114857
8,631114857
answered Sep 17 '12 at 12:17
Anshul gargAnshul garg
16516
16516
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
add a comment |
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
Careful that this does not prevent buffer overflows
– brunoais
Jan 29 '13 at 15:16
add a comment |
getline()
Now part of POSIX, none-the-less.
It also takes care of the buffer allocation problem that you asked about earlier, though you have to take care of free
ing the memory.
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
1
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
add a comment |
getline()
Now part of POSIX, none-the-less.
It also takes care of the buffer allocation problem that you asked about earlier, though you have to take care of free
ing the memory.
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
1
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
add a comment |
getline()
Now part of POSIX, none-the-less.
It also takes care of the buffer allocation problem that you asked about earlier, though you have to take care of free
ing the memory.
getline()
Now part of POSIX, none-the-less.
It also takes care of the buffer allocation problem that you asked about earlier, though you have to take care of free
ing the memory.
edited Nov 24 '11 at 17:34
answered Aug 8 '09 at 16:39
dmckeedmckee
78.6k21115205
78.6k21115205
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
1
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
add a comment |
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
1
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
Standard? In the reference you cite: "Both getline() and getdelim() are GNU extensions."
– AProgrammer
Aug 9 '09 at 8:59
1
1
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
POSIX 2008 adds getline. So GNU wen ahead and changed their headers for glibc around version 2.9, and it is causing trouble for many projects. Not a definitive link, but look here: bugzilla.redhat.com/show_bug.cgi?id=493941 . As for the on-line man page, I grabbed the first one google found.
– dmckee
Aug 9 '09 at 14:27
add a comment |
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution.
If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^n]s",&name);
printf ("%sn",name);
2
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checkingerrno
and cleaning up the allocated memory as well.
– paxdiablo
Nov 10 '17 at 1:22
add a comment |
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution.
If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^n]s",&name);
printf ("%sn",name);
2
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checkingerrno
and cleaning up the allocated memory as well.
– paxdiablo
Nov 10 '17 at 1:22
add a comment |
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution.
If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^n]s",&name);
printf ("%sn",name);
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution.
If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^n]s",&name);
printf ("%sn",name);
answered Nov 6 '17 at 1:57
Always LearningAlways Learning
491
491
2
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checkingerrno
and cleaning up the allocated memory as well.
– paxdiablo
Nov 10 '17 at 1:22
add a comment |
2
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checkingerrno
and cleaning up the allocated memory as well.
– paxdiablo
Nov 10 '17 at 1:22
2
2
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checking
errno
and cleaning up the allocated memory as well.– paxdiablo
Nov 10 '17 at 1:22
It's worth noting that this is a POSIX extension and does not exist in the ISO standard. For completeness, you should probably also be checking
errno
and cleaning up the allocated memory as well.– paxdiablo
Nov 10 '17 at 1:22
add a comment |
You may use scanf
for this purpose with a little trick. Actually, you should allow user input until user hits Enter (n
). This will consider every character, including space. Here is example:
int main()
{
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do
{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
} while (c != 'n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for
loop that takes char by char from input stream (till n
) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.
Hope this will help someone!
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
add a comment |
You may use scanf
for this purpose with a little trick. Actually, you should allow user input until user hits Enter (n
). This will consider every character, including space. Here is example:
int main()
{
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do
{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
} while (c != 'n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for
loop that takes char by char from input stream (till n
) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.
Hope this will help someone!
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
add a comment |
You may use scanf
for this purpose with a little trick. Actually, you should allow user input until user hits Enter (n
). This will consider every character, including space. Here is example:
int main()
{
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do
{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
} while (c != 'n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for
loop that takes char by char from input stream (till n
) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.
Hope this will help someone!
You may use scanf
for this purpose with a little trick. Actually, you should allow user input until user hits Enter (n
). This will consider every character, including space. Here is example:
int main()
{
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do
{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
} while (c != 'n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for
loop that takes char by char from input stream (till n
) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.
Hope this will help someone!
answered Jan 18 '15 at 11:06
akelecakelec
1,99512528
1,99512528
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
add a comment |
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
Subject to buffer overflow.
– paxdiablo
Nov 10 '17 at 1:23
add a comment |
While you really shouldn't use scanf()
for this sort of thing, because there are much better calls such as gets()
or getline()
, it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == 'r' || c == 'n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: "%s"nn", s);
return 0;
}
There's a reason whygets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse thatscanf
because at least the latter has ways to make it safe.
– paxdiablo
Nov 10 '17 at 1:25
add a comment |
While you really shouldn't use scanf()
for this sort of thing, because there are much better calls such as gets()
or getline()
, it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == 'r' || c == 'n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: "%s"nn", s);
return 0;
}
There's a reason whygets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse thatscanf
because at least the latter has ways to make it safe.
– paxdiablo
Nov 10 '17 at 1:25
add a comment |
While you really shouldn't use scanf()
for this sort of thing, because there are much better calls such as gets()
or getline()
, it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == 'r' || c == 'n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: "%s"nn", s);
return 0;
}
While you really shouldn't use scanf()
for this sort of thing, because there are much better calls such as gets()
or getline()
, it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == 'r' || c == 'n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: "%s"nn", s);
return 0;
}
edited Sep 30 '16 at 16:37
Stephen Leppik
4,52082334
4,52082334
answered Sep 29 '16 at 23:52
Ed ZavadaEd Zavada
352
352
There's a reason whygets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse thatscanf
because at least the latter has ways to make it safe.
– paxdiablo
Nov 10 '17 at 1:25
add a comment |
There's a reason whygets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse thatscanf
because at least the latter has ways to make it safe.
– paxdiablo
Nov 10 '17 at 1:25
There's a reason why
gets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse that scanf
because at least the latter has ways to make it safe.– paxdiablo
Nov 10 '17 at 1:25
There's a reason why
gets
was deprecated and removed (stackoverflow.com/questions/30890696/why-gets-is-deprecated) from the standard. It's even worse that scanf
because at least the latter has ways to make it safe.– paxdiablo
Nov 10 '17 at 1:25
add a comment |
Use the following code to read string with spaces :
scanf("[%s/n]",str_ptr);
add a comment |
Use the following code to read string with spaces :
scanf("[%s/n]",str_ptr);
add a comment |
Use the following code to read string with spaces :
scanf("[%s/n]",str_ptr);
Use the following code to read string with spaces :
scanf("[%s/n]",str_ptr);
edited Mar 3 '15 at 16:45
Skizo-ozᴉʞS
9,3471147103
9,3471147103
answered Mar 3 '15 at 16:17
Raghu GoudRaghu Goud
111
111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1247989%2fhow-do-you-allow-spaces-to-be-entered-using-scanf%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
8
Note that more idiomatic is 'malloc(sizeof(char) * 256 + 1)', or 'malloc(256 + 1)', or even better (assuming 'name' will be used strictly locally) 'char name[256+1]'. The '+1' can act as a mneumonic for the null terminator, which needs to be included in the allocation.
– Barry Kelly
Aug 8 '09 at 4:47
@Barry - I suspect
sizeof(char) + 256
was a typo.– Chris Lutz
Jul 20 '11 at 22:06