Fgets() requires enter to be hit twice after reading to char array - c

When I enter anything that evaluates to be false in function isFloat(char array[]) I need to hit enter twice to keep the program running.
If I comment out everything but the fget() command everything requires me to hit enter twice. What could be causing this? I'm flushing stdin properly and the \n is removed by strtok(). Is the printf() function causing problems? I've read that scanf() and fgets() can cause problems when used together. But here they arent.
Problem Area
printf("first number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "\n");
success = isFloat(input);
if(success)
firstNum = atof(input);
Full Code:
#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int isFloat(char array[])
{
int m = 0;
int periodCount = 0;
for(m=0; array[m] != '\000'; m++)
{
if(array[m] == '1' || array[m] == '2' || array[m] == '3' || array[m] == '4' || array[m] == '5' || array[m] == '6' || array[m] == '7' || array[m] == '8' || array[m] == '9' || array[m] == '0')
{
}
else
{
if(array[m] == '.' && periodCount == 0 && m != 0 && m+1 != '\n')
periodCount = 1;
else
return 0;
}
}
return 1;
}
void eatLine()
{
while (getchar() != '\n');
}
int main()
{
double firstNum = 0.0;
double secondNum = 0.0;
double totalNum = 0.0;
int success = 0;
int TEN_THOUSAND = 10000;
char input[TEN_THOUSAND];
//Outputs assignment header
printf("CS201 - Lab 2 - Number Adder\n\n");
printf("first number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "\n");
success = isFloat(input);
if(success)
firstNum = atof(input);
while(!success)
{
eatLine();
//The one is for testing purposes
printf("-- bad input --\n");
printf("first number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "\n");
success = isFloat(input);
if(success)
firstNum = atof(input);
}
printf("second number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "\n");
success = isFloat(input);
if(success)
secondNum = atof(input);
while(!success)
{
eatLine();
//The one is for testing purposes
printf("-- bad input --\n");
printf("second number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "\n");
success = isFloat(input);
if(success)
secondNum = atof(input);
}
//adds the numbers
totalNum = firstNum + secondNum;
//Solves ugly formatting problem by firstly including a newline
//after the input is garnered. then it outputs firstNum and totalNum
//in a field of 11 spaces with a newline terminator. This decrements
//11 to 10 on the secondNum line to compensate for the space that the + takes up.
printf("\n%11.2f\n", firstNum);
printf("%s%10.2f\n", "+", secondNum);
printf("-----------\n");
printf("%11.2f\n\n", totalNum);
return 0;
}

When I enter anything that evaluates to be false in function isFloat(char array[]) I need to hit enter twice to keep the program running.
That's because you have a line of code that expects you to enter a line of text.
while(!success)
{
eatLine(); // Culprit

Related

Something wrong with %lf in C [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 1 year ago.
I'm doing homework and I have no idea why the %lf selector isn't working. I have to take a line of characters and determine if they can be a floating point or whole number and then print that number. Here's the code:
#include <stdio.h>
int main() {
char ch;
int isNumber = 1, dot = 0, negativeMult = 10;
double result = 0;
printf("\nEnter characters: ");
scanf("%c", &ch);
while (ch != 10) {
if ((ch >= '0' && ch <= '9')) {
if (dot) {
result = result + (ch - '0') / negativeMult;
negativeMult *= 10;
} else {
result = result * 10 + (ch - '0');
}
} else
if (ch == '.')
if (dot)
isNumber = 0;
else
dot = 1;
else {
isNumber = 0;
break;
}
scanf("%c", &ch);
}
if (isNumber)
printf("\nThe number is %lf", result);
else
printf("\nEntered characters are not able to be a number.");
return 0;
}
Edit: I forgot output. Sorry.
Input: Enter characters: 123.648
Output: The number is 123.000000
the error is here:
result = result + (ch - '0') / negativeMult;
(ch - '0') / negativeMult is integer division and it is always 0
it has to be
result = result + (double)(ch - '0') / negativeMult;
some more small errors amendments:
int main(void)
{
char ch;
int isNumber = 1, dot = 0, negativeMult = 10;
double result = 0;
int scanfresult;
printf("\nEnter characters: ");
scanfresult = scanf("%c", &ch);
while (ch != '\n' && scanfresult == 1)
{
if ((ch >= '0' && ch <= '9'))
{
if (dot)
{
result = result + (double)(ch - '0') / negativeMult;
negativeMult *= 10;
}
else
{
result = result * 10 + (ch - '0');
}
}
else if (ch == '.')
if (dot)
isNumber = 0;
else
dot = 1;
else
{
isNumber = 0;
break;
}
scanfresult = scanf("%c", &ch);
}
if (isNumber)
printf("\nThe number is %f", result);
else
printf("\nEntered characters are not able to be a number.");
return 0;
}
https://godbolt.org/z/nTKdjYsz8

Getting a Segmentation fault (core dumped) error when I execute my code

I'm doing a project for my C programming class and everything was working up until I added a while loop on line 22 in order to run the code over and over to print a triangle based on a users input. The first iteration of the code still works, however when it takes the input to determine how to update the code and run it again, I get a seg fault and I can't understand why. My code is as follows:
#include <stdio.h>
#include <string.h>
int main() {
int size = 0;
char symbol = ' ';
int i = 0;
int space = 0;
int n = 0;
int oldSize = 0;
char oldSymbol = ' ';
char menuChoice = ' ';
printf("Please enter the size of the triangle (2-40): ");
scanf("%d", &size);
printf("Please enter the character you would like to use: ");
scanf(" %c", &symbol);
oldSize = size;
oldSymbol = symbol;
while (menuChoice != 'Q' || menuChoice != 'q') {
if (size < 2 || size > 40) {
size = 5;
symbol = '*';
printf("Error: Size outside bounds. Printing default triangle: \n");
}
for(i = 1; i <= size + 1; ++i, n = 0) {
for(space = 1; space <= size + 1 - i; ++space) {
printf(" ");
}
while (n != i - 1) {
printf("%c ", symbol);
++n;
}
printf("\n");
}
printf("G: Grow the current triangle\n");
printf("S: Shrink the current triangle\n");
printf("N: Draw a new triangle\n");
printf("Q: Quit\n");
scanf(" %c", menuChoice);
if (menuChoice == 'G' || menuChoice == 'g') {
size = size + 1;
} else if (menuChoice == 'S' || menuChoice == 's') {
size = size - 1;
} else if (menuChoice == 'N' || menuChoice == 'n') {
size = oldSize;
symbol = oldSymbol;
} else {
printf("Error: please enter a valid argument.");
}
}
printf("Goodbye");
}
scanf(" %c", menuChoice);
is clearly incorrect, and you know how to call this from other places in the code you uploaded. You want
scanf(" %c", &menuChoice);
I didn't spot any other similar mistakes and there are no other pointer-constructs in this code, so that should be the end of it.

Second printf is not coming up and I am unsure why

This is my code. The second printf and getchar does not pop up after hitting enter for the first scanf. I am unsure why the second printf and getchar are not working and what the fix would be.
#include <stdio.h>
int main()
{
int choice;
int i;
i = 0;
int n;
n = 1;
int p;
char message[1000];
printf("Would you like to (1) encrypt or (2) decrypt?: ");
scanf("%i\n", choice);
printf("\nType your message: ");
message[p] = getchar();
for (i = 1; (i < 1000 && message[p] != '\0');) {
message[p] = message[p] + n;
n + 1;
}
for (i = 0; (i < 1000 && message[p] != '\0');) {
message[p] = message[p] - n;
n + 1;
}
return 0;
}
Your encription method works for encription and decription. This compiles and takes in a string including spaces modifies it and prints it out.
#include <stdio.h>
int main() {
int choice;
char temp;
int i = 0;
int n = 1;
int p, b;
char message[1000];
char endmessage[1000];
printf("Would you like to (1) encrypt or (2) decrypt?: ");
scanf("%i", &choice); // change as per comment above
scanf("%c", &temp); /* temp statement to clear buffer otherwise a second character has to be typed before the next print statement is executed */
printf("Type your message: "); //prompt added for user clarity
scanf("%[^\n]", message); /* this scanf line allows for spaces in the message */
printf("\nmessage typed is: %s \n", message);
p = (sizeof( message) + 1); /* strings need to have an ending '\0'
message[p] = '\0';
if (choice == 1) {
for (i = 0; (i < 1000 && message[i] != '\0');) {
endmessage[i] = (message[i] + n);
i +=1;
}
b = (sizeof( endmessage)); // replace encripted \0 with '\0'
endmessage[b] = putchar('\0');
printf("\nYour message encripted is: %s\n\n", endmessage);
}
if (choice == 2) {
for (i = 0; (i < 1000 && message[i] != '\0');) {
endmessage[i] = message[i] - n;
i += 1;
}
b = (sizeof(endmessage) -2); // replace decripted \0 with '\0'
endmessage[b] = putchar('\0');
printf("\nYour message decripted is: %s\n\n", endmessage);
}
}

Array changing its first letter without reason

I'm making a hangman and everything works fine if you win, but if you lose it doesn't print the word it was.
I was debugging it and I found that in one of the last iterations the first character is changed to '\000' so that is why it doesn't print, but I don't understand why because there is no line where the array word is changed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define VOCABULARY_SIZE 8
#define MAX_STRING 32
#define MAX_GUESS 6
int random_number(int a, int b)
{
return a + rand() % (b - a + 1);
}
int main()
{
//random word selection
srand((unsigned)time(NULL));
const char VOCABULARY[VOCABULARY_SIZE][MAX_STRING] = {"vehicle", "building", "shirt", "pencil", "batman", "dromedary", "peach", "hangman"};
char word[MAX_STRING];
int i;
i = random_number(0, VOCABULARY_SIZE - 1);
strcpy(word, VOCABULARY[i]);
//user word
int guesses = 0, length = strlen(word);
char letters[MAX_GUESS+1];
char input[MAX_STRING];
char temp_char;
char temp_input[MAX_STRING];
do
{
printf("\nYour entered letters are: ");
printf("%s", letters);
printf("\nYour letters found are: ");
for (int j = 0; j < length; j++)
{
if (word[j] == input[j])
{
printf("%c", word[j]);
}
else
{
printf("_");
}
}
printf("\n%d-letter word. %d out of %d failures. Enter a letter: ", length, guesses, MAX_GUESS);
scanf(" %c", &temp_char);
letters[guesses] = temp_char;
letters[guesses+1] = '\0';
for (int j = 0; j < length; j++)
{
if (word[j] == temp_char)
{
input[j] = word[j];
}
}
guesses++;
printf("\nWhat is the word to guess? ");
scanf(" %s", temp_input);
} while ((strcmp(input, word) != 0 && strcmp(temp_input, word) != 0) && guesses <= MAX_GUESS);
if (strcmp(input, word) == 0 || strcmp(temp_input, word) == 0)
{
printf("\nCongratulations, the word was %s!", word);
}
else
{
printf("\nBetter luck next time... The word was %s", word);
}
}
You're writing to letters out of bounds
char letters[MAX_GUESS+1];
int guesses = 0;
do {
//...
letters[guesses+1] = '\0'; // OOPS
//...
guesses++;
//...
} while (... && guesses <= MAX_GUESS);
Nicely written code, but errors in string management.
Initialize
First time printf("%s", letters); called, letters[] is junk. Initialize it.
// char letters[MAX_GUESS + 1];
char letters[MAX_GUESS + 1] = { 0 };
Too many guess
Off by 1, lower limit.
// ... && guesses <= MAX_GUESS);
... && guesses < MAX_GUESS);
Missing '\0'
strcmp(input, word) uses input as a string, yet it lacks a null character.
Flush
Best to insure output is seen before asking for input.
fflush(stdout); // add
scanf(" %c", &temp_char);
fflush(stdout); // add
scanf(" %s", temp_input);
Unbounded input
scanf(" %s", temp_input); is worse than gets(). Research fgets().
Perhaps more issues.

Do you want to continue(y/n) issue

Do you want to continue (y/n) doesn't work in this c code. I want it to ask to enter a string when I type 'y' and exit from the program if I type n. I have tried many options, but to no avail.
Thanks for your help
do
{
i = 0, final = 0, s = 0;
printf("\n\nEnter Input String.. ");
scanf("%s", string);
while (string[i] != '\0')
if ((s = check(string[i++], s)) < 0)
break;
for (i = 0 ; i < nfinals ; i++)
if (f[i] == s )
final = 1;
if (final == 1)
printf("\n String is accepted");
else
printf("String is rejected");
printf("\nDo you want to continue.? \n(y/n) ");
}
while (getch() == 'y');
return getch();
}
if (getch() == 'n') {
// print something
return;
}
should fflush your buffer before taking char as an input
do
{//..your code
printf("\nDo you want to continue.? \n(y/n) ");
scanf("%c",&ch);
scanf("%c",&ch);
}
while (ch == 'y');

Resources