While-loop in C re-printing previous statements - c

when running the code, the while loop is re-printing the prompts asking for the user to pick an option and dimensions before printing the rectangle, when it should print the shape and then iterate through the prompts. What in the while loop would be causing those printf statements to re-print?
Code:
#include "testFile.h"
int draw_rectangle(char sym, int wid, int len){
if((wid == 0) || (len == 0)){
printf("Invalid data provided 2\n");
return 0;
}else{
int i;
int j;
for(i = 1; i <= wid; i++){
for(j = 1; j <= len; j++){
printf("%c", sym);
}
printf("\n");
}
return 1;
}
}
int main(){
int loopTrue = 1;
char character;
int length, width;
int userOption = 4;
while(loopTrue == 1){
printf("Enter 1(rectangle), 2(triangle, 3(other), 0(quit): ");
scanf("%d", &userOption);
if(userOption >= 4){
printf("Invalid data operation 1 \n");
}else if(userOption == 0){
printf("bye bye");
loopTrue = 0;
}else if(userOption == 1){
printf("enter a character, width, and length: ");
scanf("%c %d %d", &character, &width, &length);
draw_rectangle(character, width, length);
}else if(userOption == 2){
printf("not done\n");
}else if(userOption == 3){
printf("not done\n");
}
}
return 0;
}
Heres the Output

If I have understood correctly then you need to change the format string in this call of scanf
scanf("%c %d %d", &character, &width, &length);
to the following
scanf(" %c %d %d", &character, &width, &length);
^^^^
See the blank before the conversion specifier %c. It allows to skip white space characters as for example the new line character '\n' that can appear in the input buffer by pressing the Enter key.

Related

Repeat the Program for again Search Array Element

Repeat the Program for again Search Array Element.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
scanf(" %c \t",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
I want to repeat my program when user give the input of Y || y otherwise it'll exit the program.
In this code i want to make an array then search the element after this show's the results and in last repeat the code from the search the element block.
I ran your code and everything seems to be working properly except for this line:
scanf(" %c \t",&repeat);
Remove the \t from the scanf and it should work properly. You don't want to scan for a tab character, just the 'Y' or 'y' character.
Also, your use of newlines is a bit unusual. Try putting newline characters at the end of your strings as opposed to the beginning.
Updated code:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat = ' ';
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
do{
printf("Enter element to search: \n");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++) {
if(arr[i] == toSearch) {
found = 1;
break;
}
}
if(found == 1)
printf("%d is found at position %d\n", toSearch, i + 1);
else printf("%d is not found in the array\n", toSearch);
printf("Press Y to again Search Any Element in Array\nPress Any other Key to Exit the Program\n");
scanf(" %c",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
Enclose the block of code you want to repeat in a while loop, something like
bool flag = false;
while(flag==true) {
//Code block
scanf("%c",&input)
if((input == 'y') || (input == 'Y')) {flag = true;}
else {flag = false;}
}
The first method that came to my mind :
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do
{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == toSearch)
{
found = 1;
break;
}
}
if (found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
repeat = getchar();
repeat = getchar();
if(repeat == 'y' || repeat == 'Y') {
continue;
}
else {
break;
}
} while (1);
return 0;
}

C getchar() hangman game

I was given a homework assignment which tasked us with creating a simple hangman game. Below is the code I have. I am currently trying to use if else with getchar() to ask the user to input a lowercase letter and see if it matches one of the letters in the word they are supposed to guess. From my very limited experience the code I have should work and when I step through the program it appears as if it should run properly, but when I actually run the program it seems to skip over the second getchar(). Anyone have any suggestions or help?
#include "stdio.h"
#include "math.h"
int main(void) {
int(a);
int(b);
float(x);
float(c);
float(e);
int word[4] = {116, 101, 115, 116};
int guess[4];
c == 0;
a == 0;
b == 0;
printf("Welcome to Hangman\n");
printf("Input a word--one lower case letter at a time\n");
printf("Enter Guess: ");
x = getchar();
if (x > 122) {
printf(" Error, character must be a lowercase letter");
} else
if (x < 97) {
printf(" Error, character must be a lowercase letter");
} else
if (x == 116) {
printf("t is correct\n");
printf("%d", word[0]);
printf(" _");
printf(" _");
printf(" %d ", word[3]);
e = getchar();
if (e == 101) {
printf("e is correct\n");
printf("%d", word[0]);
printf(" %d", word[1]);
printf(" _");
printf(" %d ", word[3]);
} else
if (e == 115) {
printf("s is correct\n");
printf("%d", word[0]);
printf(" _");
printf(" %d", word[2]);
printf(" %d", word[0]);
} else {
printf(" You guessed wrong");
}
} else
if (x == 101) {
printf("e is correct\n");
printf("_");
printf(" %d", word[1]);
printf(" _");
printf(" _ ");
} else
if (x == 115) {
printf("s is correct\n");
printf("_");
printf(" _");
printf(" %d", word[2]);
printf(" _ ");
} else {
printf(" You guessed wrong");
}
}
When you input a character that you want getchar to read, you end it with the Enter key right? That Enter key will also be put into the input buffer of stdin (which is what getchar reads from) as a newline, '\n'.
That means for each input you give, you actually input two characters.
You need to skip that newline. This can easily be done by just adding a second getchar after the first, like for example
x = getchar();
getchar(); // Read the newline from the Enter key
There is already a good answer, but to clarify the
problem a little bit more, here is a simple piece of code.
The function get_character will return the first entered character
and consume all following characters until the next '\n'.
It is not going to block if one character is EOF.
#include<stdio.h>
int get_character(void);
int main(void)
{
printf("character > ");
int c = get_character();
while(c != EOF && c != 'q')
{
printf("You entered %c\n", c);
printf("character > ");
c = get_character();
}
}
int get_character(void)
{
int c = getchar(), next_c;
if(c == EOF)
{
return EOF;
}
next_c = getchar(); // consume all \n
while(next_c != '\n' && next_c != EOF)
{
fprintf(stderr, "WARNING: consumed non-newline character: 0x%x\n", next_c);
next_c = getchar();
}
return c;
}
By the way: You are able to solve the hangman way faster:
int get_character(void);
#define MAX_TRIALS 3
#define WORD_LEN 4
int main(void)
{
char word[WORD_LEN + 1] = "test";
char correct[WORD_LEN] = {0, 0, 0, 0};
int trials = 0;
while(1)
{
if(trials > MAX_TRIALS)
{
printf("You failed. The word was: %s\n", word);
return 0;
}
printf("character > ");
int c = get_character();
if(c == EOF)
{
printf("bye\n");
return 0;
}
int i, this_char_correct = 0;
for(i = 0; i < WORD_LEN; i++)
{
if(c == word[i])
{
correct[i] = 1;
this_char_correct = 1;
}
if(correct[i])
{
printf("%c", word[i]);
}
else
{
printf("_");
}
}
if(!this_char_correct)
{
trials++;
}
int word_done = 1;
for(i = 0; i < WORD_LEN; i++)
{
word_done &= correct[i];
}
if(! word_done)
{
printf("\nYou have %d trials left\n", WORD_LEN - trials);
}
else
{
printf("\nYou got it.\n");
return 0;
}
}
}
This is just a piece of proof-of-concept code there might be way more elegant ways to solve this.

How to read multiple integers from a single line?

Input is some integers separeted by spaces in one line, like this:
enter numbers: 12 41 2
program should get each integers and show the sum:
sum: 55
how can i do that?
edit:I tried this but it is unable to detect enter key. It should stop and show sum when enter is pressed.
printf("\nEnter numbers: ");
int sum =0;
int temp;
while( scanf("%d",&temp))
{
sum+=temp;
}
printf("Sum: %d",sum);
#include <stdio.h>
int main(){
printf("\nEnter numbers: ");
int sum =0, temp;
char ch;
while(2 == scanf("%d%c", &temp, &ch)){
sum+=temp;
if(ch == '\n')
break;
else if(ch != ' '){
fprintf(stderr, "Invalid input.\n");
return -1;
}
}
printf("Sum: %d\n", sum);
return 0;
}
#include <stdio.h>
int main(void){
char line[128], *p=line;
int sum = 0, len, n;
printf("enter numbers: ");
scanf("%127[^\n]", line);
while (sscanf(p, "%d%n", &n, &len)==1){
sum += n;
p += len;
}
printf("sum: %d\n", sum);
return 0;
}

scanf check in while loop to restrict integer input

I am writing a code asking the user to input 10 integers, which are then fed to him backwards. I would like to create a "scanf check" to restrict character input. The while loop works insofar that it doesn't accept char, but it skips a integer input.
int main()
{
int i = 0, number[10] = {0};
char buf[128] = {0};
for (i = 0; i < 10; i++)
{
printf("Please input number %d : ", i+1);
while(scanf("%d", &number[i]) != 1)
{
scanf("%s", &buf);
printf("Sorry, [%s] is not a number. Please input number %d : ", &buf, i);
}
}
for (i = 0; i < 10; i++)
{
printf("\n Number %d is %d", (10-i), number[9-i]);
}
return EXIT_SUCCESS;
}
As pointed out by H2CO3, don't use scanf, an alternative is fgets and strtol:
int i, number[10] = {0};
char buf[128], *p;
for (i = 0; i < 10; i++) {
printf("Please input number %d : ", i+1);
while (1) {
fgets(buf, sizeof(buf), stdin);
if ((p = strchr(buf, '\n')) != NULL) {
*p = '\0';
}
number[i] = (int)strtol(buf, &p, 10);
if (p == buf || *p != '\0') {
printf("Sorry, [%s] is not a number. Please input number %d : ", buf, i + 1);
} else {
break;
}
}
}
for (i = 0; i < 10; i++) {
printf("\n Number %d is %d", (10-i), number[9-i]);
}
return EXIT_SUCCESS;
The code works fine for integer also. The only mistake I found is while printing the sorry message, you are printing just i, it should be i+1.
int i = 0, number[10] = {0};
char buf[128] = {0};
for (i = 0; i < 10; i++)
{
printf("Please input number %d : ", i+1);
while(scanf("%d", &number[i]) != 1)
{
scanf("%s", &buf);
printf("Sorry, [%s] is not a number. Please input number %d : ", &buf, i+1);
}
}
for (i = 0; i < 10; i++)
{
printf("\n Number %d is %d", (10-i), number[9-i]);
}

Reading in and recording a number in C

This is a homework problem. I have a C program that takes user input for a number of people's first names, last names, and ages. Right now it works and prints out the names to the console correctly, but it is not printing out the right ages, and I can't figure out what I'm doing wrong. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int choice;
int i = 0;
int x,k,l;
fputs("How many people would you like to add? ", stdout);
scanf(" %d", &choice);
fflush(stdout);
int ch;
while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF)
{
}
char firstName[choice][20];
char lastName[choice][20];
int age[choice][3];
char first[20];
char last[20];
int a[3];
for (x = 0; x < choice; x++)
{
for (l = 0; l < 3; l++)
{
age[x][l] = 0;
a[l] = 0;
}
}
while(i < choice)
{
printf("Enter the first name of person ");
printf(" %d", i);
printf(": ");
fgets(first, 20, stdin);
for (k = 0; k < 20; k++)
{
firstName[i][k] = first[k];
}
i++;
}
i = 0;
while(i < choice)
{
printf("Enter the last name of person ");
printf(" %d", i);
printf(": ");
fgets(last, 20, stdin);
for (k = 0; k < 20; k++)
{
lastName[i][k] = last[k];
}
i++;
}
i = 0;
while(i < choice)
{
fputs("Enter the age of person ", stdout);
printf(" %d", i);
printf(": ");
scanf(" %d", &a);
fflush(stdout);
for (l = 0; l < 3; l++)
{
age[i][l] = a[l];
}
i++;
}
int sh;
while((sh = getchar()) != EOF && sh != '\n');
if (sh == EOF)
{
}
for (x = 0; x < choice; x++)
{
printf("First name ");
printf(": ");
printf("%s ", firstName[x]);
printf("\n");
printf("Last name ");
printf(": ");
printf("%s ", lastName[x]);
printf("\n");
printf("Age ");
printf(": ");
printf("%d ", &age[x]);
printf("\n");
}
return 0;
}
If you copy/paste this code it will run, but the age outputted will be incorrect. Can anyone tell me why this is? Thank you!
scanf(" %d", &a);
That should be:
scanf(" %d", &a[0]);
And the printf should be printf("%d", age[x][0]);
You want to read into the first element of the array, not the entire array. You want to print out the first element of the array, not the address of the array.
A better solution would probably be not to make age an array of 3 at all. Each person only has one age. The changes would be:
int age[choice];
int a;
scanf(" %d", &a);
age[choice] = a;
printf("%d ", age[x]);

Resources