inputting array of characters in c

Ishan Bansal

I have written this code to input two array of characters a and b of size 5 each.

When I give the input :

abcde
abcde

the output b[2] should be c but it is giving as b.

#include <stdio.h>

using namespace std;

int main(){

   char a[5], b[5];
   int i;
   for(i = 0; i < 5; i++){
       scanf("%c", a + i);
   }

   for(i = 0; i < 5; i++){
       scanf("%c", b + i);
   }

    printf("%c", b[2]);
}
Spikatrix

Remember pressing Enter after typing abcde for the first scanf? This character is consumed by the second scanf during the first iteration of the second for loop.

You can fix it by adding

scanf("%*c");

or

getchar();

between the two for loops. This will scan and discard the newline character.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Inputting individual characters in C

From Dev

Inputting Number in Array and Displaying it?

From Dev

Inputting numbers into an array

From Dev

Java ASCII Characters Inputting As A String

From Dev

Inputting, splitting, and sorting in C

From Dev

inputting strings into a multidimensional character array?

From Dev

Inputting an array to python function by hand

From Dev

Inputting UTF-8 characters into the Bash CLI

From Dev

Is there any way in C to terminate scanf() inputting in array without ctrl+d?

From Dev

C - Inputting string into an int variable?

From Dev

Inputting images into array or matrix elements in MATLAB

From Dev

Segmentation error while inputting last array element

From Dev

MEthod not returning the correct result when inputting an array

From Dev

Codeblocks inputting a text file array error

From Dev

Inputting string read from a .txt file into an array

From Dev

Array assignment for characters: C programming

From Dev

Testing stored array characters in C

From Dev

Characters adding in array in C#

From Dev

Generate array of unique characters in C

From Java

Inputting Huge Binary Numbers C++

From Dev

inputting data with pointers in class in c++

From Dev

C# Reading from html and inputting into .Text

From Dev

Inputting non-array elements in a method which receives an array

From Dev

Non null terminated array of characters in c++

From Dev

C - printing a grid with a pointer to an array of characters

From Dev

Objective-C: Splitting a word into an array of characters

From Dev

C - printing a grid with a pointer to an array of characters

From Dev

storing string and characters in two dimensional array (C)

From Dev

How to copy text to array of characters in C

Related Related

HotTag

Archive