C/Console/Console Read String
Содержание
Get a string from stdin: how to use gets
<source lang="cpp">
- include <stdio.h>
int main() {
char string [256]; printf ("Enter your address: "); gets (string); printf ("Your address is: %s\n",string); return 0;
}
</source>
Get string from console and assign it to a char pointer
<source lang="cpp">
- include <stdio.h>
int main(void) {
char *p, str[80]; printf("Enter a string: "); p = gets(str); if(p) /* if not null */ printf("%s %s", p, str); return 0;
}
</source>
Get string from console and output it
<source lang="cpp">
- include <stdio.h>
int main(void) {
char str[80]; printf("Enter a string: "); if(gets(str)) /* if not null */ printf("Here is your string: %s", str); return 0;
}
</source>
Read formatted data from string: how to use sscanf
<source lang="cpp">
- include <stdio.h>
int main () {
char sentence[] = "This is a line."; char str [20]; int i; sscanf (sentence,"%s %*s %d",str,&i); printf ("%s -> %d\n",str,i); return 0;
}
</source>
Read string: A simple scanf and printf pair
<source lang="cpp">
- include <stdio.h>
int main(void) {
char str[80]; printf("Enter a string: "); scanf("%s", str); printf(str); return 0;
}
</source>
Use fgets to read string from standard input
<source lang="cpp">
- include <stdio.h>
- include <string.h>
int main(void) {
char str[80]; int i; printf("Enter a string: "); fgets(str, 10, stdin); /* remove newline, if present */ i = strlen(str)-1; if( str[ i ] == "\n") str[i] = "\0"; printf("This is your string: %s", str); return 0;
}
</source>