How to Read in a String in C++

Internship at OpenGenus

Become this book -> Issues on Array: For Interviews and Competitive Programming

In this article, nosotros have explained how to take string input in C Programming Language using C lawmaking examples. We take explained different cases similar taking i word, multiple words, entire line and multiple lines using different functions.

Tabular array of contents:

  1. String input using scanf Office
    1.i. Reading One Give-and-take
    1.2. Reading Multiple Words
    1.3. Reading Multiple Words to Form a Line
    one.4. Reading an entire line
  2. Using getchar
  3. Reading Entire Line using gets()
  4. Read One Line at a Time from a File using fgets()
  5. Reading Multiple Lines

Let united states of america learn these techniques using C code examples.

Cord input using scanf Function

The input function scanf can exist used with %south format specification to read in a string of characters.

Reading One Give-and-take

For Example :

              char instr[10]; scanf("%s",instr);                          

The problem with the scanf function is that it terminates its input on the get-go white space it finds. A white space includes blanks,tabs,carraige returns,form feeds and new lines.

Therefore, if the following line of text is typed :

              Hullo Boy                          

then but the string "HELLO" volition be read into the assortment accost , since the blank space later on the word 'NEW' will finish the reading of cord.
The unused locations are filled with garbage.

The scanf office automatically terminates the string that is read with a null character and therefore, the character array should exist large plenty to hold the input string plus the aught character. Notation that dissimilar previous scanf calls, in the example of graphic symbol arrays, the ampersand (&) is not required earlier the variable name.

Reading Multiple Words

If we want to read the entire line "How-do-you-do BOY", and so we may utilise two character arrays of appropriate sizes.

              char instr1[x], instr2[10]; scanf("%s %south", instr1,instr2);                          

Information technology will assign the string "HELLO" to instr1 and "Male child" to instr2.

              #include<stdio.h> #include<cord.h> int primary() {     char instr[100];        printf("Enter a string\n");     scanf("%s",bin);     printf("String is : \north");     puts(bin);          return 0; }                          

If we requite "WELCOME TO OPENGENUS" equally input it will only read WELCOME and displays it every bit output.

To overcome this problem we tin can make different arrays for all the words nowadays in the cord .

Reading Multiple Words to Form a Line

              #include<stdio.h> #include<string.h> int primary() {     char instr1[100],instr2[100],instr3[100],instr4[100];          printf("Enter the string of four words\n");     scanf("%s",instr1);     scanf("%due south",instr2);     scanf("%s",instr3);     scanf("%s",instr4);     printf("String is : \n");          printf("%southward %southward %south %s" ,instr1,instr2,instr3,instr4 );          render 0; }                          

It volition accept four words in four dissimilar character arrays and displays on the output screen.

Reading an entire line

We have seen that scanf with %s or %ws can read simply strings without whitespaces.
However, C supports a format specification known as the edit set conversion code %[..] that can be used to read a line containing a variety of characters, including whitespaces.

              char instr[100]; scanf("%[^\n]",instr);                          

A similar method to to a higher place:

              char instr[100]; scanf("%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]", instr);                          

Using getchar

We tin utilize it repeatedly to read successive unmarried characters from the input and place them into a grapheme assortment. Thus, an entire line of text can exist read and stored in an array. The reading is terminated when the new line character ('\n')
is entered and the null character is then inserted at the cease of the string.

              #include<stdio.h> #include<cord.h> principal() {     char instr[100] , ch;     int c = 0;     printf("Enter the line \n");     exercise     {          ch = getchar();          instr[c]=ch;          c++;     }while(ch != '\n');      c=c-1;     instr[c]='\0';     printf("%s \due north", instr); }                          

Reading Entire Line using gets()

Another method of reading a cord of text containing whitespaces is to use the library function gets available in the <stdio.h> header file.
It reads characters from the keyboard until a new line character is encountered and then appends a zippo character to the string.
Unlike scanf, information technology does non skip whitespaces.

For example :

              char instr[100]; gets (line); printf("%s", instr);                          

It volition reads a line from the keyboard and displays it on the screen.

The last program tin exist also written as :

              char instr[100]; printf("%s" , gets(line));                          

Please notation that C does not check for array bounds , so be careful not to input more than graphic symbol that tin can be stored in the string variable used.

A complete program to demonstrate working of gets :

              #include<stdio.h> #include<cord.h> int main() {     char instr[100];          printf("Enter a string\north");     scanf("%[^\due north]",instr);     printf("The output is:-\northward");     puts(bin);          render 0; }                          

This program will work perfectly fine and information technology will take the entire string as input from the keyboard and displays it on the output screen.

Read Ane Line at a Time from a File using fgets()

The function fgets() takes three parameters that is :

  1. string_name
  2. string_max_size
  3. stdin

We can write it as :

              fgets(string_name,string_max_size,stdin);                          

For Instance :

              #include<stdio.h> #include<string.h> int main() {     char instr[100];          printf("Enter the string\north");     fgets(instr,100,stdin);     printf("The cord is:-\due north");     puts(bin);          return 0; }                          

It volition take the unabridged string as input from the keyboard and displays the entire screen on the output screen.

Reading Multiple Lines

The following programme reads multiple line from the keyboard.

              #include<stdio.h> int chief() {     int s[100];     printf("Enter multiple line strings\n");     scanf("%[^\r]due south",s);     printf("Entered Cord is\n");     printf("%due south\n",s);     return 0; }                          

Question

Which of the post-obit is the correct input statement for reading an unabridged cord from keyboard ?

All of them are right.

gets(str);

scanf("%[^\northward]",str);

fgets(instr,100,stdin);

All these methods are discussed in the article that is gets() , scanf("%[^\north]",str); and fgets()

Question

A character array instr[] stores the "HELLO". What will be the length of array instr[] requires to shop the string completely ?

six

five

four

None of these

As the word hello is v characters long and in that location will be a null character at end , nosotros require an assortment of size 6.

Question

State Truthful or Faux : "The input function gets has one string parameter ."

True

False

The input function gets has one string parameter which reads characters from the keyboard until a new line character is encountered and and so appends a null character to the string.

Then, with this commodity at OpenGenus, we take seen all the possible methods to take input string in C programming language.

warddefe2001.blogspot.com

Source: https://iq.opengenus.org/how-to-take-string-input-in-c/

0 Response to "How to Read in a String in C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel