Getting Input in one Line Inside a Loop - c

I am working on a c programming problem. In the problem I have to get
two chars in one line. I have to repeat the process for n times. consider the following code:
char c[100],p[100];
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%c %c", &c[i], &p[i]);
I used this code to get the value of n, and then get the values in one line for the array of c and p. But I am getting some unexpected result and I don't know the reason. Need help.

scanf("%c %c", &c[i], &p[i]);
should be
scanf(" %c %c", &c[i], &p[i]);
There is a newline character at the end of input value n so you need to ignore it by placing a space before %c
Note the value of n should be n<=100 else you have array out of bound access.
Make sure you null terminate the strings once the characters are scanned or have
char c[100] = "";
char p[100] = "";
In C a valid string should be null terminated.
If you are looking for a VLA(Variable length array) based on the size of n then have your array as
scanf("%d",&n);
char c[n];
char p[n];
for(int i=0; i<n-1; i++)
scanf(" %c %c", &c[i], &p[i]);

You have to store the null value after reading characters into the character array.
char c[100],p[100];
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%c %c", &c[i], &p[i]);
c[i] = '\0';
p[i] = '\0';

Related

program stops working if i use a value used by user

#include<stdio.h>
//prints a shape using users input
int main() {
int i, j ;
char a ;
i = 0 , j= 0;`
printf("enter your charecter :");
scanf("%s", &a);
for ( j = 0; j < 5; j++) {
for ( i = 0; i < 5; i++) {
printf("%s", a);
}
printf("\n");
}
return 0;
}
program stops after input by user
&a does not refer to a string. %s will write all characters entered and nul terminate so will overrun the the single character to which &a refers.
You have the same format specifier mismatch for the output. The format specifier for a single character is %c, however in this case you could use getchar() / putchar().

printing string from the array

as you can see this while I run this it works perfectly till "The array is " but cant show the string that I enter
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
int size;
char arr[size];
printf("input size of array ");
scanf("%d", &size);
printf("\ninput elements of array ");
for (int i = 0; i < size; i++)
{
scanf("%s", &arr[i]);
}
printf("\nThe array is ");
for (int i = 0; i < size; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
There are multiple things wrong with this code.
int size;
char arr[size];
You are declaring a char array arr with size elements, but size is not yet initialized yet and may be any value. Also note that "deciding the size of an array at runtime" is only valid in modern C (C99 onwards).
You should first read size and only after the scanf declare arr.
for (int i = 0; i < size; i++){
scanf("%s", &arr[i]);
}
You read a string (%s) with scanf and try to store it in a char (&arr[i] points to the ith char in arr). Every C string is atleast 1 character long (the terminating \0 character), you are trying to store multiple characters in a single char.
Instead use
scanf("%s", arr);
Note that scanf is not safe. Even if you enter more than size characters, it will still try to store them in arr. That leads to undefined behaviour, because arr is too small. Instead you can use fgets, that lets you set the number of characters to read.
for (int i = 0; i < size; i++){
printf("%s\n", arr[i]);
}
Here you are trying to print a String (%s), but you are passing a char (arr[i] is the ith char in arr).
Instead use
printf("%s\n", arr);

Why is this reverse string program not working?

I am new to C programming so please do forgive my naivety. The following program when outputted fails to print the last character of the input string as the first character of the output string.
For example:
Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh
Why is the o not printing?
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf("%d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf("%c", &string[i]);
}
printf("The reversed string is: ");
for (int i = (n - 1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
There is a side effect you take care of:
After scanf("%d", &n);, there is a pending newline in the input stream buffer.
When you later input n characters, scanf("%c", &string[i]) first reads the pending newline, then the n-1 first characters you type and the remainder of your input stays in the input buffer.
scanf() is a very clunky function. It is difficult to use properly.
Here is a way to fix your problem:
#include <stdio.h>
int main() {
char string[10000];
int i, n, c;
printf("Enter no. of elements: ");
if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
return 1;
// read and discard pending input
while ((c = getchar()) != '\n' && c != EOF)
continue;
printf("Enter string: ");
for (i = 0; i < n; i++) {
if (scanf("%c", &string[i]) != 1)
break;
}
// the above loop could be replaced with a single call to fread:
// i = fread(string, 1, n, stdin);
printf("The reversed string is: ");
while (i-- > 0) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Your scanf() should start with a space( more info about that ). Here is the code:
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf(" %d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf(" %c", &string[i]);
}
/* Just to be safer. */
string[n] = '\0';
printf("The reversed string is: ");
for (int i = (n-1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Adding the space to the format string enables scanf to consume the
newline character from the input that happens everytime you press
return. Without the space, string[i] will receive the
char '\n'
So, merely one space is put before format specifier %c at line 11.
scanf(" %c", &string[i]);

Switching letters in a string in C

I'm not sure why this code does not work.
This code is supposed to, for example, switch all a's in the string to b's, and all b's to a's and print the result.
input:
abcd
a b
c d
Intended output:
badc
Code:
int main()
{
int n, m, i, j;
scanf("%d %d", &n, &m);
char s[n+1], x[m+1], y[m+1];
scanf("%s", s);
for(i=0; i<m; i++)
{
scanf("%c", &x[i]);
scanf("%c", &y[i]);
}
for(j = 0; j < m; j++)
{
for(i = 0; i<n; i++)
{
if(s[i] == x[j])
s[i] = y[j];
else if(s[i] == y[j])
s[i] = x[j];
}
}
printf("%s", s);
return 0;
}
As I commented you need a space before the %c in these lines
scanf("%c", &x[i]);
scanf("%c", &y[i]);
to prevent the %c format type reading the white-space left in the input buffer by previous scanf calls. Change to
scanf(" %c", &x[i]);
scanf(" %c", &y[i]);
Your logic is correct. You just need to put a space before %c specifier in both of the scanf
for(i=0; i<m; i++)
{
scanf(" %c", &x[i]);
scanf(" %c", &y[i]);
}
and it will work. This is because the \n leftover by the previous scanf is read by second scanf and same is happening for the space in between the the input characters a b and c d. A space before %c in scanf will consume all white-spaces.
You can change loop to replace characters in only one iteration
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(s[i] == x[j])
{
s[i] = y[j];
break;
}
if(s[i] == y[j])
{
s[i] = x[j];
break;
}
}
}
In addition to https://stackoverflow.com/a/33397902/2410359
Code does not insure that s is null character terminated at print time - leads to undefined behavior. Should use for(i = 0; s[i] && i<n; i++) to prevent overwriting it.
This may account for excessive time usage.
OP posts below as input. Certainly 2 numbers must precede that for scanf("%d %d", &n, &m);
abcd
a b
c d

Why scanf or fgetc does not work as expected

Following is my code and it is not stopping for first index and I wonder why ? Same is the result with scanf
#include<stdio.h>
void main()
{
int n = 0, i = 0;
char arr[10];
printf("How many characters do u want to enter ");
scanf("%d", &n);
//printf("\n\t%d", n);
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
char ch = fgetc(stdin);
arr[i] = ch;
//putchar(arr[i]);
}
i = 0;
printf("You have entered characters are \n");
for(i = 0; i < n; i++)
{
printf("arr[%d] = %c\n", i, arr[i]);
}
printf("\n");
}
When I run this code I get following
How many characters do u want to enter 5
Enter 0 character-->
Enter 1 character-->
program does not wait for first character to input.
There is an endline character on the input stream that is left there by scanf("%d",&n) and is read by the first fgetc
Same is the result with scanf
Are you using scanf correctly? Try the following (don't miss the space before the %c):
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
scanf(" %c", &arr[i]);
}
Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.
So, when fgetc starts reading from STDIN, it reads a character and leaves the newline character. So you should either use scanf() i.e. scanf(" %c", &arr[i]); as suggested by Cubbi. Or you need to discard that newline character otherwise. You may use this
for(i = 0; i < n; i++)
{
printf("Enter %d character-->\n",i);
char ch = fgetc(stdin); // newline is consumed here
if(ch=='\n')
ch = fgetc(stdin); // you get the expected value
arr[i] = ch;
//putchar(arr[i]);
}

Resources