scanf("%s") stops at a space. To read a whole line, use fgets:
#include <stdio.h>
int main() {
char line[100];
fgets(line, 100, stdin);
printf("You typed: %s", line);
return 0;
}Input (what the user types)
I love learning C
Output
You typed: I love learning C
lineis where the text goes.100is the size of the array, sofgetsnever writes too much. That makes it safe.stdinmeans "read from the keyboard" (standard input).
Removing the newline
fgets keeps the Enter key ('\n') at the end of the line. That's why we didn't need \n in the printf above. Usually you want to remove it. strcspn(line, "\n") finds where the '\n' is, and we put '\0' there:
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
fgets(name, 50, stdin);
name[strcspn(name, "\n")] = '\0';
printf("[%s] has %d characters\n", name, (int) strlen(name));
return 0;
}Input (what the user types)
Ada Lovelace
Output
[Ada Lovelace] has 12 characters
Tip: Copy that line –
name[strcspn(name, "\n")] = '\0';– every time you usefgets.
Text to number
atoi (from <stdlib.h>) turns text like "42" into the number 42. atof does the same for decimals:
#include <stdio.h>
#include <stdlib.h>
int main() {
char a[10] = "42";
char b[10] = "2.5";
int n = atoi(a);
double d = atof(b);
printf("%d %.1f\n", n + 1, d * 2);
return 0;
}Output
43 5.0
Number to text
sprintf works like printf, but writes into a string instead of the screen:
#include <stdio.h>
int main() {
char label[30];
int level = 7;
sprintf(label, "Level-%03d", level);
printf("%s\n", label);
return 0;
}Output
Level-007
Remember:
fgetsreads a whole line safely. Remove its'\n'withstrcspn.