C Tutorial/String/String Read

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

Ask the user for his first and last name.

<source lang="cpp">#include <stdio.h>

   #include <string.h>
   int main() {   
       char first[100];
       char last[100]; 
       char full[200];            
       printf("Enter first name: ");  
       fgets(first, sizeof(first), stdin);
       printf("Enter last name: ");   
       fgets(last, sizeof(last), stdin);  
       strcpy(full, first);   
       strcat(full, " "); 
       strcat(full, last);
       printf("The name is %s\n", full);  
       return (0);
   }</source>
Enter first name: string
Enter last name: last
The name is string
 last

Reading Strings

The standard function fgets can be used to read a string from the keyboard.

The general form of an fgets call is:


<source lang="cpp">fgets(name, sizeof(name), stdin);</source>

The arguments are:

name is the name of a character array. sizeof(name) indicates the maximum number of characters to read. stdin is the file to read.

Read string from keyboard

<source lang="cpp">#include <stdio.h> int main() {

  char me[20];

  printf("What is your name?");
  scanf("%s",&me);
  printf("Darn glad to meet you, %s!\n",me);

  return(0);

}</source>

What is your name?1
      Darn glad to meet you, 1!