C/Console/Console Read String

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Get a string from stdin: how to use gets

#include <stdio.h>
int main()
{
  char string [256];
  
  printf ("Enter your address: ");
  
  gets (string);
  
  printf ("Your address is: %s\n",string);
  return 0;
}


Get string from console and assign it to a char pointer

  
#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;
}


Get string from console and output it

  
#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;
}


Read formatted data from string: how to use sscanf

#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;
}


Read string: A simple scanf and printf pair

  
#include <stdio.h>
int main(void)
{
  char str[80];
  printf("Enter a string: ");
  scanf("%s", str);
  printf(str);
  return 0;
}


Use fgets to read string from standard input

#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;
}