Reading a line of text Using getchar()

C Programming Language String in C Language (Article) String in C Language (Program)

3122

Program:

<span class="com">/* 
 Author: Atnyla Developer
*/</span><span class="pln">

</span><span class="com">#include</span><span class="pln"> </span><span class="str">&lt;stdio.h&gt;</span><span class="pln">
</span><span class="kwd">int</span><span class="pln"> main</span><span class="pun">()</span><span class="pln">
</span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">char</span><span class="pln"> line</span><span class="pun">[</span><span class="lit">30</span><span class="pun">],</span><span class="pln"> ch</span><span class="pun">;</span><span class="pln">
    </span><span class="kwd">int</span><span class="pln"> i </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln">
    printf</span><span class="pun">(</span><span class="str">"Enter name: "</span><span class="pun">);</span><span class="pln">
    </span><span class="kwd">while</span><span class="pun">(</span><span class="pln">ch </span><span class="pun">!=</span><span class="pln"> </span><span class="str">'\n'</span><span class="pun">)</span><span class="pln">    </span><span class="com">// terminates if user hit enter</span><span class="pln">
    </span><span class="pun">{</span><span class="pln">
        ch </span><span class="pun">=</span><span class="pln"> getchar</span><span class="pun">();</span><span class="pln">
        line</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> ch</span><span class="pun">;</span><span class="pln">
        i</span><span class="pun">++;</span><span class="pln">
    </span><span class="pun">}</span><span class="pln">
    line</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="str">'\0'</span><span class="pun">;</span><span class="pln">       </span><span class="com">// inserting null character at end</span><span class="pln">
    printf</span><span class="pun">(</span><span class="str">"Line is: %s"</span><span class="pun">,</span><span class="pln"> line</span><span class="pun">);</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln">
</span><span class="pun">}</span>

Output:

Enter name: Rambo Azmi
Line is: Rambo Azmi
Press any key to continue . . .

Explanation:

This program reads a full line of text and store each character one by one.

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.