I have been asked to modify a program to read characters rather than numbers.
i modified the array into a char array. changed the two "%d" to "%c" as below
void main (void)
{
char a[100];
int counter;
int b;
counter = 0;
printf("please enter the length of the array: ");
scanf("%d", &b );
while (counter != b)
{
printf("please enter character: ");
scanf("%c", &a[counter]);
counter++;
}
a[counter] = '\0' ;
counter = 0;
while (a[counter] != '\0')
{
printf("\n");
printf("%c",a[counter]);
counter++;
}
}
when i run this the program does this:
please enter the length of the array: (4)
please enter character: please enter character: (a)
please enter character: please enter character: (a)
a
a
() are used to indicate the user inputs.
would be really good if i could get some help.
You have to remember that scanf leaves the newline in the input buffer, so when you try to read a character it will that newline.
The solution is very simple: Tell scanf to read and discard leading whitespace, by adding a space in the format code:
scanf(" %c", &a[counter]);
/* ^ */
/* | */
/* Note space here */
Related
I read chars until '\n', convert them to int and sum the numbers until the result is only one digit.
I can't use mod or .
The first run went well, but the second one keep running and not waiting to \n.
any reason for keeping the '\n'?
#include<stdio.h>
int main(){
char str[8], conv_str[8],c;
int i,val,ans = 0;
while(1){
printf("Enter 8 values(0-9) :\n");
scanf("%[^\n]", str); // Scan values to str untill \n
for(i = 0;i < 8;i++){
val = str[i]-48; //convert from asci to int
ans += val;
}
while(ans > 9){
// itoa convert int to string, str(the input) is the buffer and 10 is the base
itoa(ans,conv_str,10);
ans = (conv_str[0]-48) + (conv_str[1]-48) ;
}
printf("the digit is: %d", ans);
printf("\ncontinue? (y/n)\n");
scanf("%s", &c);
if (c == 'n')
break;
memset(str, 0, sizeof(str));
}
return 0;
}
TIA
You have multiple problems in the code. Some of them are
scanf("%s", &c); is wrong. c is a char, you must use %c conversion specifier for that.
You never checked for the return value of scanf() calls to ensure success.
While scanning for character input, you did not clear the buffer of any existing inputs. Any existing character, including a newline ('\n') already present in the buffer will be considered as a valid input for %c. You need to clear the buffer before you read a character input.
This program is not giving the correct output; and it is taking input once instead of 't' times, while entering for the first time in the for-loop.
This problem is HEADBOB (https://www.codechef.com/problems/HEADBOB)
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
for(t; t>0; t--)
{
int J=0, Y=0, N=0, I=0, len=0;
if(len==0)
scanf("%d", &len);
char ar[len];
for(J=0; J<len; J++)
{
scanf("%c",&ar[J]);
if(ar[J]=='Y')
Y++;
else if(ar[J]=='N')
N++;
else if(ar[J]=='I')
I++;
}
if(I>0)
printf("INDIAN\n");
else
{
if((Y&&!N)||(N&&!Y))
printf("NOT SURE\n");
else if(Y&&N) printf("NOT INDIAN\n");
}
}
}
INPUT:
NUMBER OF TEST CASES
NUMBER OF CHARACTERS
N NUMBER OF CHARACTERS
SAMPLE INPUT & OUTPUT OF ABOVE CODE:
INPUT:
5
5
NNYNN
OUTPUT:
NOT INDIAN
Check, if scanf("%c", &ar[j]) is reading whitespace characters! Think about
scanf(" %c", &ar[j]);
That means to skip all whitespace characters (space, tabs, \ns, etc).
Or even better:
scanf("%d", &len);
char ar[len + 1]; // + 1 for 0-termination
scanf(" %s", ar); // skip all whitespace characters, then read a string
Reading full string in one shot is a lot faster.
The problem is that the second scanf (scanf("%d", &len);) leaves a newline character in the standard input stream (stdin). This character is then consumed by the third scanf (scanf("%c",&ar[J]);) in the first iteration of the loop.
Changing
scanf("%d", &len);
to
scanf("%d%*c", &len);
will fix the problem. %*c tells scanf to read and discard a character.
I am trying to run the following code but the program accepts only one string and displays the output immediately without waiting for the second string to be entered. The program is for 2 string concatenation. Here is the code :-
#include <stdio.h>
main()
{
int i, j, len=0;
char name[100], abc[100];
printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",&name);
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",&abc);
for(i=0; name[i]!='\0'; i++)
len++;
for(j=0; abc[j]!='\0'; j++)
{
len++;
name[len]=abc[j];
}
printf("\nThe Concatenated String Is =\t");
puts(name);
}
Use fgets instead of scanf, also you were incrementing len at the wrong place:
#include <stdio.h>
#include <string.h>
int main() {
int len = 0;
char name[100], abc[100];
printf("\nPlease Enter String 1 =\t");
fgets(name, 100, stdin);
len = strlen(name) - 1;
name[len] = 0;
printf("\nPlease Enter String 2 =\t");
fgets(abc, 100, stdin);
abc[strlen(abc) - 1] = 0;
strcpy(name+len, abc);
printf("\nThe Concatenated String Is =\t");
puts(name);
return 0;
}
Use the following scanf instead:
scanf("%[^\n]",name);
.....
scanf(" %[^\n]",abc);
Please refer to this scanf() manual page for more detail of how to use scanf().
You have to throw away the newline character ('\n').
Try:
while(getchar() != '\n')
continue;
after each scanf
I would like to suggest you not to use scanf. Better to use fgets instead.
By the way the reason that your program accepts only one string and displays the output immediately without waiting for the second string to be entered is the \n character left behind by the first scanf after pressing the Enter key. To eat up this newline character you may use gatchar() after first scanf.
printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",name);
getchar();
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",abc);
Other two mistakes are:
1. Wrong increment of len
for(i=0; name[i]!='\0'; i++)
len++;
for(j=0; abc[j]!='\0'; j++)
{
name[len++]=abc[j];
}
2. Reason for weird output is the string is not NUL terminated. Add this line after second for loop.
name[len] = '\0'; // add this to null terminate your string.
Here is your working Code
should be
scanf("%[^\n]%*c", name);
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]%*c", abc);
for(i=0;name[i]!='\0';i++)
len++;
for(j=0;abc[j]!='\0';j++){
name[len]=abc[j];
len++;
}
name[len]='\0';
In my code given below if I press 'y' for once it will reapeat, but then it is not asking for next tome to repeat (or press 'y').Can someone help why this code is terminated after one loop?
main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');
}
That will be because stdin is buffered. So you are probably entering the string of a y followed by a \n (newline character).
So the first iteration takes the y, but the next iteration doesn't need any input from you because the \n is next in the stdin buffer. But you can easily get around this by getting scanf to consume the trailing whitespace.
scanf("%c ",&choice);
NOTE: the space after the c in "%c "
But, your program can get stuck in an infinite loop if the input ends with a y. So you should also check the result of the scanf. e.g.
if( scanf("%c ",&choice) <= 0 )
choice = 'n';
You should read out the newline character after that scanf() call. Otherwise, that gets into choice the next time around and so the while loop comes out.
#include<stdio.h>
int main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
choice = getchar();
getchar();
}
while(choice=='y');
return 0;
}
At the first character of the scanf format string, insert a space. This will clear out all white space characters from stdin before reading data.
#include <stdio.h>
int main (void)
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf(" %c",&choice); // note the space
}while(choice=='y');
return 0;
}
/*
Program to calculate trip and plan flights
*/
#define TRIP 6
#define DEST 1
#include <stdio.h>
int error_dest(int type_num, int cont_num, int dest_code, int check);
int main(void)
{
int check, type_num, cont_num, index, i, dest_code, trip_num, row, col;
int travelint[TRIP][DEST], travelarea[TRIP];
char area_code, S, M, L, N, P, K, R, C, U, W, O;
trip_num = 7;
while (trip_num > TRIP)
{
printf("Please enter the number of trips:");
scanf("%d", &trip_num);
if ( trip_num < TRIP)
{
printf("Valid trip number. Please proceed to enter destination code.\n");
}
else
{
printf("Invalid trips. Please enter no more then 6 trips.\n");
}
}
/*********************************************************************************/
for (i=0; i < trip_num ; i++) /*destination code input*/
{
printf("Please enter destination code:");
scanf("%d", &dest_code); /*input of destination code*/
check = error_dest(type_num, cont_num, dest_code, check);
if (check == 2)
{ travelint[i][0]=dest_code; }
else
{
while (check == 1)
{
printf("Please enter destination code:");
scanf("%d", &dest_code); /*input of destination code*/
check = error_dest(type_num, cont_num, dest_code, check);
if (check == 2)
{ travelint[i][0]=dest_code; }
}
}
printf("Please select from the following that best describes your destination:\n");
printf("S Small city - population under 50,000\n");
printf("M Medium city - population between 50,000 and 500,000\n");
printf("L Large city - pop. over 500,000\n");
printf("N Natural formation like a mountain, a lake, a cave, a geyser, a fjord, a canyon, etc.\n");
printf("P Designated park or reserve such as a wildlife refuge, a national park, a bioreserve, or a protected marine area\n");
printf("K Man made landmark like the Great Wall of China, the Taj Mahal, or Stonehenge\n");
printf("R State or province or region of a country\n");
printf("C Whole country\n");
printf("U Multiple countries like traveling through Europe\n");
printf("W Ocean voyage\n");
printf("O Any other type of destination - such as visiting the sites of the seven wonders of the world\n");
printf("Please enter the Area Letter code:");
scanf("%c", &area_code);
}
/*******************************************************************************/
/*print for destination_code*/
for (row = 0; row < trip_num; row++)
{
for (col=0; col < DEST; col++)
printf("Trip[%d] = %d\n", row+1, travelint[row][col]);
}
return 0;
}
error_dest(type_num, cont_num, dest_code, check)
{
cont_num = dest_code / 10000; /*math for error check*/
type_num = dest_code/1000 - cont_num*10;
if ( (cont_num <= 7) && (cont_num > 0) && (type_num <= 5) && (type_num >=0) )
{ /* loop for checking destination code*/
check = 2 ;
return check;
}
else
{
printf("%d is a invalid code\n", dest_code);
check = 1;
return check;
}
}
for some strange reason at the scanf("%c", &area_code); it just runs ahead and print the dest_code array without letting me input any character and I'm not sure what exactly I am doing wrong.
If you're looking to grab only one character, perhaps it would be better to use getchar() instead of scanf()?
Basically what's happening is this: you print the "Please enter the number of trips" message to the screen. The user types in 4 and then hits the enter key, which means the stdin buffer looks like this: "4\n". You then call scanf with the "%d" format string. scanf looks at the stdin buffer, and sees the 4. It looks at the next character, which is the newline, and sees it's not part of a number (as %d specifies), so it is done fulfilling the format string and leaves the file pointer at the newline. It converts the char '4' to an integer 4 and places it in trip_num and returns.
The next time you call scanf, it picks up where it left off at the newline. The format string this time is "%c", so it just grabs the next character from the buffer which is currently the newline ("\n"), places it in dest_code, and returns. If you want the scanf function to skip over the whitespace in this case, you have to explicitly tell it by adding a space before the "%c" format for the second scanf (destination code). Then scanf will skip over all whitespace (including that newline) until it encounters a non-whitespace character that it places in dest_code.
TL;DR: Change the second scanf call to scanf(" %c", &dest_code). And fix the other errors others have pointed out so other bugs won't manifest.
You may print area_code after scanf, I guess it may be '\n' which is the last character of the dest_code line you entered.
You should empty the buffer before reading a character from stdin:
int c = 0;
while (c != '\n' && c != EOF)
{
c = getchar();
}
then you can read your character using scanf or replace it with getchar.
This may or may not help, but previously stated you probably need to put the getchar() into the while loop. You may also need the fgets to grab the stdin from the keyboard.
while(1){
printf("Enter Message Type:");
fflush(stdout) ;
// scan msg.hdr from received message.
scanf("%d", &(msg.m_hdr));
while(getchar() != '\n'){}
printf("Enter your Message:");
fflush(stdout);
// grab data from keyboard
fgets(msg.m_data, sizeof(msg.m_data), stdin);
Use "fflush(stdin)" before you enter the character, i.e. before the "printf" statement for the character. It will flush out the input buffer and thus you can scan the desired character. Or simply give a Space before the "%c" command. Like---------- scanf(" %c", &area_code); ---------------