Reputation: 997
I'm new to C and I would like to know if it's possible to write into a string the character \n
from the keyboard by using scanf()
function.
The code that I'm using is this: (sorry for the Italian variables words)
void riempi_array_stringhe (char* stringhe[], int lunghezza_array)
{
for (int i = 0; i < lunghezza_array; i++) {
stringhe[i] = (char*) malloc(sizeof(char) * 100);
printf("Insert a new string: ");
scanf("%s", stringhe[i]);
}
}
I tried type shift + enter, alt + enter, or to insert \n as input but not works at all.
Thanks in advance!
Upvotes: 0
Views: 444
Reputation: 8534
There is a [
specifier. Quote from scanf(2)
[
— Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating null byte.
Example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str[10];
for (int i = 0; i < 10; i++) {
str[i] = (char *)malloc(sizeof(char) * 100);
printf("Insert a new string: ");
scanf("%[^~]", str[i]);
printf("Your input: %s\n", str[i]);
}
return 0;
}
To end the input we should input ~
and then Enter
or press Ctrl+D
(EOF). We can specify other characters to terminate the input. For example, scanf("%[^X]", str[i]);
will terminate the input after user inserts an X
and then Enter
.
Please note, to prevent your buffer overrun, you should always specify the width
of the sequence equals to the buffer size minus one (for NUL
character), i.e.:
scanf("%99[^~]", str[i]); // read no more than 99 symbols + NUL
Upvotes: 3