Reputation: 245
I'm trying to make a program that scans multiple chars each time the program loops and then prints all the scanned characters at the end. However, the program only prints the first character scanned each in each loop. Does anyone have any suggestions as how to fix this? Also, I'm just a beginner.
#include <stdio.h>
void f1();
void f2();
int i;
char letters[20];
int main()
{
f1();
printf("%s", letters);
}
void f1()
{
for(i=0; i<5; i++)
{
f2();
}
}
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[i]);
}
Upvotes: 2
Views: 2069
Reputation: 19874
The problem is in each loop you scan just a single character so when you print the array each character which is the first character of the input is printed out.
scanf("%s", &letters[i]);
You need to use a 2D array like
char letters[5][20];
To scan 5 strings of 20 characters each,the whole code would look like
#include <stdio.h>
void f1();
void f2();
int i;
char letters[5][20];
int main()
{
f1();
int k;
for(k=0;k<5;k++)
printf("%s\n", letters[k]);
return 0;
}
void f1()
{
for(i=0; i<5; i++)
{
f2();
}
}
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[i]);
}
Upvotes: 0
Reputation: 2547
Assuming you will take only two characters as input at a time:
Replace
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[i]);
}
With
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[2*i]);
}
Upvotes: 1