Skip to content Skip to sidebar Skip to footer

Read Multiple Lines Into One String C++

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have explained how to take string input in C Programming Language using C code examples. We accept explained different cases like taking one discussion, multiple words, unabridged line and multiple lines using different functions.

Table of contents:

  1. String input using scanf Office
    1.one. Reading 1 Word
    ane.2. Reading Multiple Words
    1.three. Reading Multiple Words to Form a Line
    1.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 us learn these techniques using C code examples.

String input using scanf Part

The input role scanf can be used with %s format specification to read in a cord of characters.

Reading One Word

For Example :

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

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

Therefore, if the following line of text is typed :

              Hello Male child                          

so only the string "How-do-you-do" will be read into the array address , since the blank infinite after the word 'NEW' will terminate the reading of cord.
The unused locations are filled with garbage.

The scanf function automatically terminates the string that is read with a null grapheme and therefore, the graphic symbol assortment should exist large enough to hold the input string plus the nix graphic symbol. Note that unlike previous scanf calls, in the example of character arrays, the ampersand (&) is non required earlier the variable name.

Reading Multiple Words

If we want to read the entire line "Howdy Boy", then nosotros may utilize two graphic symbol arrays of advisable sizes.

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

Information technology volition assign the string "HELLO" to instr1 and "BOY" to instr2.

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

If we give "WELCOME TO OPENGENUS" as input information technology volition merely read WELCOME and displays information technology as output.

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

Reading Multiple Words to Class a Line

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

Information technology will take iv words in four different character arrays and displays on the output screen.

Reading an unabridged line

Nosotros have seen that scanf with %s or %ws can read only strings without whitespaces.
However, C supports a format specification known equally the edit gear up conversion code %[..] that can be used to read a line containing a multifariousness of characters, including whitespaces.

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

A similar method to higher up:

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

Using getchar

We can use information technology repeatedly to read successive single characters from the input and place them into a grapheme array. Thus, an entire line of text tin can be read and stored in an assortment. The reading is terminated when the new line character ('\n')
is entered and the null character is then inserted at the end of the cord.

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

Reading Unabridged Line using gets()

Some other method of reading a string of text containing whitespaces is to utilize the library role 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 cypher character to the string.
Different scanf, it does not skip whitespaces.

For case :

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

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

The concluding program tin can be also written as :

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

Please annotation that C does not check for array bounds , and so be careful not to input more than character that can be stored in the cord variable used.

A complete program to demonstrate working of gets :

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

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

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

The function fgets() takes iii parameters that is :

  1. string_name
  2. string_max_size
  3. stdin

We can write information technology as :

              fgets(string_name,string_max_size,stdin);                          

For Example :

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

It will take the entire string every bit input from the keyboard and displays the entire screen on the output screen.

Reading Multiple Lines

The post-obit plan reads multiple line from the keyboard.

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

Question

Which of the following is the right input statement for reading an entire string from keyboard ?

All of them are correct.

gets(str);

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

fgets(instr,100,stdin);

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

Question

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

six

5

four

None of these

As the give-and-take hello is five characters long and there will be a null character at end , we require an array of size 6.

Question

State True or Imitation : "The input function gets has one string parameter ."

Truthful

Fake

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

And so, with this article at OpenGenus, we take seen all the possible methods to take input cord in C programming language.

robertscancest.blogspot.com

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

Post a Comment for "Read Multiple Lines Into One String C++"