Switching letters in a string in C - 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

Related

Trouble with a C program

I had a homework. The condition was: "Make a program in witch will be displayed how many 'A' and 'B' where typed". I tried and this is what i made:
#include <stdio.h>
int main()
{
int n, i, a=0, b=0;
char cr;
scanf ("%i", &n);
for (i=0; i<=n; i++) {scanf ("%c", &cr); if (cr='A') a++; else if (cr=='B') b++;}
printf ("A-%i\n", a);
printf ("B-%i", b);
}
The problem is when i type for example 10, it only lets me type 5 characters, not 10. Why?
The program can be made with for, while or do while.
Problems and solutions
you need to use scanf(" %c", %cr) to prevent the program from reading trailing whitespaces
You should be using if (cr == 'A') and not if (cr = 'A') because you are comparing and not assigning
the loop should be for (i = 0; i < n... not for (i = 0; i <= n.. as the loop would ask for 1+ input from the specified range
#include <stdio.h>
int main() {
int n, a = 0, b = 0;
char cr;
printf("Enter number of tries :\n");
scanf ("%i", &n);
for (int i = 0; i < n; i++) {
printf("Enter char\n");
scanf(" %c", &cr);
if (cr == 'A') a++;
else if (cr == 'B') b++;
}
printf ("A-%i\n", a);
printf ("B-%i", b);
}

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]);

There is a missing element in my 2D array when it's printed

#include<stdio.h>
#include<stdlib.h>
#define MSIZE 10
int main()
{
int Size, gen, i, j;
printf("Enter number of generations\t");
scanf("%d", &gen);
printf("\nEnter size of the matrix (max size is %d and min is 2)\t", MSIZE);
scanf("%d", &Size);
if (Size > MSIZE) {
printf("\nSize should not be more than %d", MSIZE);
return 1;
}
if (Size < 2) {
printf("\nSize should not be less than 2");
return 1;
}
char **m = (char**) calloc(Size, sizeof(char*));
for (i=0; i<Size; i++)
{
m[i] = (char*) calloc(Size, sizeof(char));
}
printf("Enter matrix of first generation\n");
for (i=0; i<Size; i++) {
for (j=0; j<Size; j++) {
scanf("%c", &m[i][j]);
/*to make sure*/
printf("%c ", m[i][j]);
}
printf("\n\n");
}
}
This is the first part of my program which should be about the death game for Conway. I think, the problem is in the input function, because if I fill it inside the program by myself (not by input) it will be printed right.
I think, the problem is in the input function, because if I fill it
inside the program by myself (not by input) it will be printed right.
You need a space before "%c" in scanf() to consume a previous newline/enter:
for (i=0; i<Size; i++) {
for (j=0; j<Size; j++) {
scanf(" %c", &m[i][j]);
/*to make sure*/
printf("%c ", m[i][j]);
}
printf("\n\n");
}
When you hit enter on the previous scanf(), a newline is placed in the input buffer. Adding a space in front of %c tells scanf() to skip that newline (and other whitespace).

Getting Input in one Line Inside a Loop

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';

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