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]);
Related
How do I find the frequency of all the characters and not only one character (using functions and strings)?
Example input: aaaaabbccc
Expected output:
'a' : 5
'b' : 2
'c' : 3
#include <stdio.h>
int main() {
char string[1000], character;
int amount = 0;
printf("Enter a word: ");
fgets(string, sizeof(string), stdin);
printf("Enter any character from the word to find the frequency of the character: ");
scanf("%c", &character);
for (int i = 0; string[i] != '\0'; ++i) {
if (character == string[i])
++amount;
}
printf("Frequency of %c = %d", character, amount);
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am studying the c language in our class I create some code to find a some number inside other array but when I try it with char value my code is not working in same as working with int value.
This is my code:
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
//printf("%d\t", (i+1));
//if ( i + 1 == num ) {
// scanf("%c", &a[i]);
//} else {
scanf("%c", &a[i]);
//}
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf("%c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
I try to fixed many time but each time I get error, so the above one is working but it scape the some input value during input.
Thank you WhozCraig, user3121023 for your advices, the whitespace in scanf(" %c", &a[i]); and scanf(" %c", &ele); make some unwanted inputs so this is a my code and its working like charm. :))
I just add space before the %c and every thing is okay.
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
printf("%d\t", (i+1));
scanf(" %c", &a[i]);
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf(" %c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
There is a problem in your program that causes surprising behavior:
scanf("%d", &num) reads a number from standard input but leaves the newline typed by the user pending as the next character to be read.
Further calls to scanf("%c", &a[i]); read this pending newline and num-1 more characters from the user, leaving the rest of his input pending...
The final scanf("%c", &ele); reads whatever byte is pending in stdin, either a character from the user or the pending newline.
Hence the program behaves as if it does not execute the last scanf().
You should read input from the user one line at a time with fgets() or flush the pending newline with a loop:
#include <stdio.h>
int main() {
int num, i, c;
char a[99], ele;
printf("Enter the number of character:");
// get the length of array by the num value
if (scanf("%d", &num) != 1 || num < 0 || num > 99)
return 1;
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
printf("Enter the characters on a single line: \n");
// a loop for getting values for our a[array]
for (i = 0; i < num; i++) {
if (scanf("%c", &a[i]) != 1)
return 1;
}
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
printf("Enter the character to be searched: ");
// get the value for ele, to use ele for searching inside our a[array]
if (scanf("%c", &ele) != 1)
return 1;
// consume the rest of the line typed by the user
while ((c = getchar()) != EOF && c!= '\n')
continue;
// use a for loop
for (i = 0; i < num && ele != a[i]; i++) {
i++;
}
if (i < num) {
printf("Character %c found at the offset %d\n\n\n", ele, i);
} else {
printf("Character %c Not Found!\n\n\n", ele);
}
return 0;
}
I want to do a program that ask to the user to give one character, then enter... until he wants to stop by pressing enter and no caracters.
Then, the program will say: "you gave the caracters ...."
for example:
give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')
result: You gave the caracters: kl
My code doesnet work because when i just press enter, nothing happen. Here is the code:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}
printf("The string is: ");
while (j < i) {
printf("%s", str[j]);
j += 1;
}
return 0;
}
You can do it with c = getchar(); or c = fgetc(stdin) function:
#include <stdio.h>
#define N 1000
int
main ()
{
int i = 0;
int j = 0;
int c;
char str[N];
while (1)
{
c = fgetc(stdin); // or c = getchar();
if ( (c != EOF) && (c != 0x0A ) ) // 0x0A = 'nl' character
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
This is my string!
element number str[1]=T
element number str[2]=h
element number str[3]=i
element number str[4]=s
element number str[5]=
element number str[6]=i
element number str[7]=s
element number str[8]=
element number str[9]=m
element number str[10]=y
element number str[11]=
element number str[12]=s
element number str[13]=t
element number str[14]=r
element number str[15]=i
element number str[16]=n
element number str[17]=g
element number str[18]=!
The string is: This is my string!
Or you can use your original scanf("%s", &str1);
#include <stdio.h>
#define N 1000
int main ()
{
int i = 0;
int k = 0;
int c;
int len;
char str[N];
char str1[N];
scanf("%s", &str1);
len = strlen(str1);
for(k = 0; k < len; k++)
{
c = str1[k];
if ( (c != EOF) && c != '\n') // EOF will work for ^D on UNIX
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
12345
element number str[1]=1
element number str[2]=2
element number str[3]=3
element number str[4]=4
element number str[5]=5
The string is: 12345
As stated in this answer scanf will not return until you give it a string, i.e. it skips whitespace.
As suggested in the answer and in general, using fgets is the better option.
Edit: A way to accomplish what you want would look like this:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
do {
printf("element number str[%d] : ", i);
fgets(&str[i], 3, stdin);
i++;
} while (str[i - 1] != '\n');
printf("The string is: ");
while (i > j) {
printf("%c", str[j]);
j++;
}
return 0;
}
In the fgets you use the number 3 because pressing enter gives both a newline character [/n] and a return carriage [/r].
Actually recently i found a problem where i need to count occurrence a given(by oj) char in a given string(with test case).So i write this code but output is not as i desired.I'm a beginner so i'll be greatly thankful for any kind of instructive advice or help.THANK YOU.
#include<stdio.h>
#include<string.h>
int main ()
{
int ara [123];
char s[1000];
int l, j, i, len;
char c;
scanf ("%d\n", &l);
while (l >= 0){
for (i = 65; i <= 122; i++)
{
ara[i] = 0;
}
fgets(s, 1000, stdin);
len = strlen(s);
for (i = 0;i <= len; i++)
{
ara[s[i]]++;
}
scanf(" %c\n", &c);
j = c;
printf("count : %d\n", ara[j]);
l--;
}
return 0;
}
The problem is that scanf is leaving a newline in the input to be read as the target sentence.
You can get around this by using fgets and sscanf instead. I also added some cues to make it easier to know what is expected.
#include <stdio.h>
#include <string.h>
int main (void)
{
int ara [128]; // increased array size
char s[1000];
char t[10];
int l, j, i, len;
char c;
printf("Enter how many loops:\n");
fgets(t, sizeof t, stdin); // replace scanf
sscanf (t, "%d\n", &l); // with sscanf
while (l > 0){ // changed end test
for (i = 'A'; i <= 'z'; i++) // replaced magic numbers
{
ara[i] = 0;
}
printf("Enter the string:\n");
fgets(s, sizeof s, stdin);
len = strlen(s);
for (i = 0;i <= len; i++)
{
ara[s[i]]++;
}
printf("Enter the letter:\n");
fgets(t, sizeof t, stdin); // replace scanf
sscanf (t, "%c\n", &c); // with sscanf
j = c;
printf("count : %d\n", ara[j]);
l--;
}
return 0;
}
Program session
Enter how many loops:
2
Enter the string:
one two three four
Enter the letter:
o
count : 3
Enter the string:
three seven
Enter the letter:
e
count : 4
Note that ideally, you should also check the function return values from fgets and sscanf.
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]);
}