I am trying have a program end when the user hits the Enter key. For some reason it doesn't seem to work. When I use "char c is not equal to enter key" it takes in an extra integer in c (the last inputted integer). What is the problem with this code?
#include <stdio.h>
#include <stdlib.h>
#define framenumber 4
int test1 =0;
int test2=1;
int main(void)
{
int mainarray[framenumber][2] = {0}, nHP = 3, takein, iPT;
char c = getchar();
printf("Enter: ");
while(1)
{
char c = getchar();
if(c == '\n') {
printf("here");
}
else
{
printf("not enter\n");
takein = atoi(&c);
for (iPT = 0; mainarray[iPT][test2] != takein && iPT < framenumber; iPT++);
if (mainarray[iPT][test2] != takein)
{
//search for a victim
do {
nHP = (nHP + 1) % framenumber;
} while ( !( mainarray[nHP][test1] == 1 ? mainarray[nHP][test1] = 0 : 1 ) );
//update the page table
mainarray[nHP][test1] = 1;
mainarray[nHP][test2] = takein;
}
else
{
mainarray[iPT][test1] = 1;
}
puts("page table:");
for (iPT = 0; iPT < framenumber; iPT++)
{
printf("%s %d, %d.\n", iPT == (nHP + 1) % 4 ? ">": " ", mainarray[iPT][test1], mainarray[iPT][test2]);
}
putchar('\n');
printf("Enter: ");
}
}
return 0;
}
Do not create block variable. (In while loop).
char c='\0'; /* initialize with 0 */
printf("Enter: ");
while(c!='\n') /* loop terminate condition */
{
c= getchar(); /* remove declaration */
if(c =='\n')
{
printf("here");
}
else
{
getchar(); /* read (eat) an extra input */
printf("not enter\n");
....
Related
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);
}
}
In this factorial program when entered any non numeric or negative number then the program should ask to renter the value but in the output the program is getting terminated.
Is it because I am returning -1 in display() function? If so then is it compulsory to return a variable (or other function) value to a function if the function is meant to return a value?
#include <stdio.h>
int display();
void fact_fun(int num_fact);
int main() {
int num = 0;
char next;
next = display();
if (next == -1) { //WHEN ANY CHARACTER OR NEGATIVE NUMBER IS ENTERED IT WILL ASK TO RENTER
printf("\nOnly positive number is allowed");
display();
}
while (next >= 0) { //WHEN NEGATIVE NUMBER IS ENTERED IT WILL END THE LOOP
num = next;
fact_fun(num);
next = display();
}
return 0;
}
int display() {
char inp[10] = { 0 };
int input;
int index = 0;
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
while (((input = getchar()) != EOF) & (index < 10)) {
if ((input >= '0') && (input <= '9')) {
inp[index++] = input;
} else
if (input == '\n')
break;
else
return -1;
}
input = atoi(inp);
return input;
}
void fact_fun(int num_fact) {
int fact = 1;
if (num_fact == 0) {
printf("\nFactorial of %d is 1", num_fact);
return;
} else {
for (int i = 1; i <= num_fact; i++) {
fact = fact * i;
}
printf("\nFactorial of %d is %d", num_fact, fact);
}
}
Also when I press ENTER KEY I am getting output as below:
Factorial of %d is 1
Enter number to find factorial or press ENTER KEY to exit:
And when enter \n the program gets terminate. As per my understanding it should treat the Enter key and \n same. If not then what is the difference and how should I check for ENTER KEY value?
User input is line buffered by default. It is much simpler for your purpose to read input one line at a time from the user, parse it to assert input validity and compute the factorial only for valid input.
Note also that you can simplify the computation as the special case for 0 is redundant with the code for the general case. You should also check for potential arithmetic overflow as the computation may easily exceed the range of type int and produce undefined behavior.
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int display();
void fact_fun(int num_fact);
int main() {
int num;
while ((num = display()) >= 0) {
fact_fun(num);
}
return 0;
}
int display() {
char buf[256];
char *p;
long value;
for (;;) {
printf("Enter number to find factorial or press ENTER KEY to exit: ");
if (fgets(buf, sizeof buf, stdin) == NULL || *buf == '\n')
return -1;
errno = 0;
value = strtol(buf, &p, 0);
if (p == buf) {
printf("Invalid input: not a number\n");
} else {
if (value < 0) {
printf("Invalid input: negative values not allowed\n");
} else
if (errno != 0 || value > INT_MAX) {
printf("Invalid input: value too large for type int\n");
} else {
return (int)value;
}
}
}
void fact_fun(int num_fact) {
int fact = 1;
for (int i = 1; i <= num_fact; i++) {
if (fact > INT_MAX / i) {
printf("Invalid input: arithmetic overflow\n");
return;
}
fact = fact * i;
}
printf("Factorial of %d is %d\n", num_fact, fact);
}
Here is your code with some corrections. There were two problems.
The first is that you have to finish reading the input until you reach an end of the line or EOF.
The second is that you need two error codes, one for invalid input, and a second for no-input. (Your comment in the code indicates that you want to exit on no-input).
#include <stdio.h>
#include <stdlib.h>
int display();
void fact_fun(int num_fact);
int main() {
//int num = 0;
char next;
while( 1 ) {
next = display();
if (next == -2) {
break;
}
if (next == -1) {
//WHEN ANY CHARACTER OR NEGATIVE NUMBER IS ENTERED IT WILL ASK TO RENTER
printf("\nOnly positive number is allowed");
}
else {
fact_fun(next);
}
}
return 0;
}
int display() {
char inp[10] = { 0 };
char c;
int input = 0;
int index = 0;
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
while ( ((c = getchar()) != EOF) && (c != '\n') && (index < 10)) {
if ( (c >= '0') && (c <= '9') ) {
inp[index++] = c;
} else {
input = -1;
break;
}
}
// Finish inputting the line
while ( (c != EOF) && (c != '\n') ) {
c = getchar();
}
if ( !input ) {
if ( index )
input = atoi(inp);
else
input = -2;
}
return input;
}
void fact_fun(int num_fact) {
int fact = 1;
if (num_fact == 0) {
printf("\nFactorial of %d is 1", num_fact);
return;
} else {
for (int i = 1; i <= num_fact; i++) {
fact = fact * i;
}
printf("\nFactorial of %d is %d", num_fact, fact);
}
}
In this factorial program when entered any non numeric or negative number then the program should ask to renter the value
The while loop in your main() function only loops to ask for new numbers until input() returns a negative number. You have even documented it:
while(next>=0) //WHEN NEGATIVE NUMBER IS ENTERED IT WILL END THE LOOP
...
When you do return -1 in input(), the function returns -1, which will set next to -1 and end the loop. The program then exists shortly after that.
There is nothing inherently wrong with using a return statement to return -1 from a user defined function. It's quite normal and common to do things like that.
I've got this homework assignment where we get the user to enter the amount of lines of strings they desire, they then proceed to enter them which gets stored in a 2D Array (thus creating an array of strings). Then a switch case menu will be displayed which should
Search a character entered by the user, returns the amount of times the character occurred in the array
Search a word entered by the user, returns the amount of times the word occurred in the array
Have the user enter a specified word length and return the amount of times words of the specified length occur.
I have a couple problems with my code. The program runs without errors from the compiler. The searchByCharacter function works fine but the searchByWord only returns a value of 0 regardless of any word inputted and nothing happens after I input a number for the searchByLength function. The program freezes after I enter a length once I select the searchByLength function. I've been at this for a while and I don't know where I'm going wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 80
#define MAX_LINES 10
#define WORD_LENGTH 20
void readText(char text[][MAX_LINE_LENGTH], int n)
{
int i;
printf("Enter %d number of lines:\n", n);
for(i = 0; i < n; i++)
{
scanf(" %[^\n]s", text[i]);
}
}
int searchByCharacter(char text[][MAX_LINE_LENGTH], int n, char c)
{
int i, charCount = 0, j = 0;
for(i = 0; i < n; i++)
{
j = 0;
while(text[i][j] != '\0')
{
if(text[i][j] == c)
{
charCount++;
}
j++;
}
}
return charCount;
}
int searchByWord(char text[][MAX_LINE_LENGTH], int n, char * keyword)
{
int i, wordCount = 0;
for(i = 0; i < n; i++)
{
int j = 0;
int lengthOfWord = 0;
char wordCheck[WORD_LENGTH];
char * currentLine = text[i];
while(currentLine[j] != '\0')
{
if (currentLine[j] == ' ' || currentLine[j] == '\n' || currentLine[j] == ',' || currentLine[j] == '.' ||
currentLine[j] == ';')
{
wordCheck[lengthOfWord] = '\0';
int matchingWord = strcmp(wordCheck, keyword);
if(matchingWord == 0)
{
wordCount++;
}
lengthOfWord = 0;
j++;
continue;
}
wordCheck[lengthOfWord] = currentLine[n];
lengthOfWord++;
j++;
}
}
return wordCount;
}
int searchByLength(char text[][MAX_LINE_LENGTH], int n, int wordLen)
{
int i, lengthCount = 0;
for(i = 0; i < n; i++)
{
int lengthOfWord = 0;
int j = 0;
char * currentLine2 = text[i];
while(currentLine2[j] != '\0')
{
if (currentLine2[j] == ' ' || currentLine2[j] == '\n' || currentLine2[j] == ',' || currentLine2[j] == '.' ||
currentLine2[j] == ';')
{
if(lengthOfWord == wordLen)
{
lengthCount++;
}
lengthOfWord = 0;
n++;
continue;
}
lengthOfWord++;
n++;
}
}
return lengthCount;
}
int main(void)
{
char textInput[MAX_LINES][MAX_LINE_LENGTH];
printf("Enter number of lines (<10): ");
int textLines = 0;
scanf("%d", &textLines);
while(textLines < 1 || textLines > 10)
{
printf("Invalid Input.\n");
printf("Enter number of lines (<10): ");
scanf("%d", &textLines);
}
if(textLines >= 1 && textLines <= 10)
{
readText(textInput, textLines);
int menuActive = 1;
while(menuActive)
{
printf("\nText Analysis\n----\n");
printf("1-Search By Character\n2-Search By Word\n3-Search By Length\n0-Quit\nPlease enter a selection: ");
int selection;
scanf("%d", &selection);
switch(selection)
{
case 0:
menuActive = 0;
break;
case 1:
printf("Selected 1\n");
printf("Enter a character to search: ");
char characterSearch;
scanf(" %c", &characterSearch);
int characterwordCount = searchByCharacter(textInput, textLines, characterSearch);
printf("\nNumber of occurence of %c = %d", characterSearch, characterwordCount);
break;
case 2:
printf("Selected 2\n");
printf("Enter a word to search: ");
char wordSearch[MAX_LINE_LENGTH];
scanf(" %s", wordSearch);
int lengthwordCount = searchByWord(textInput, textLines, wordSearch);
printf("\nNumber of occurence of %s = %d", wordSearch, lengthwordCount);
break;
case 3:
printf("Selected 3\n");
printf("Enter search length: ");
int wordLength;
scanf(" %d", &wordLength);
int wordLengthwordCount = searchByLength(textInput, textLines, wordLength);
printf("Number of words with length %d = %d", wordLength, wordLengthwordCount);
break;
default:
printf("Invalid Input.\n");
}
}
printf("You Have Quit!\n");
}
return 0;
}
I have a school assignment to make a hangman game. The game works how I want it to except for one small glitch. If the user entered word is 4 letters or less, the hidden word is displayed with an extra "_\377" at the end. When the user entered word is 5 letters or more, then there is no glitch. I am hoping that someone would be kind enough to help me trouble shoot the problem. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int letterfinder(char string[], char a, int vari)
{
int length = strlen(string);
int i = vari;
int val = 0;
while( i <= length && val != 1)
{
if( string[i] == a)
{
val = 1;
}
i++;
}
if( val == 0)
{
return 100;
}
else
{
return i;
}
}
int main()
{
char inWord[] = "1111111111111111111111111111";
char outWord2[] = "1111111111111111111111111111";
char guess;
int gameover = 0;
int trys = 10;
int vari = 0;
printf("Please enter a word: ");
gets(inWord);
printf("%s\n", inWord);
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
int i2 = 0;
int j2 = 0;
int i3 = 0;
i2 = strcspn(inWord, outWord2);
char outWord[80];
while(i3 < i2)
{
outWord[i3] = '1';
i3++;
}
while(j2 < i2)
{
outWord[j2] = '-';
j2++;
}
puts(outWord);
while(gameover != 1 )
{
printf("What is your guess: ");
scanf("%s", &guess);
vari = 0;
if(letterfinder(inWord, guess, vari) == 100)
{
printf("Wrong!");
trys--;
printf("You have %d attempts left\n", trys);
if(trys == 0)
{
gameover = 1;
printf("You ran out of attempts. Game over\n");
}
}
else
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = (letterfinder(inWord, guess, vari));
while(letterfinder(inWord, guess, vari) != 100)
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = letterfinder(inWord, guess, vari);
}
puts(outWord);
}
int value = 0;
i3 = 0;
while( i3 <= i2)
{
if( outWord[i3] == '-')
{
value = 1;
}
i3++;
}
if(value != 1)
{
printf("Congratulations, you have guessed the word!\n");
gameover = 1;
}
}
return 0;
}
Your code has Undefined Behaviour. In the cases it "works" it is only by chance/luck. char guess; scanf("%s", &guess); That causes memory corruption as you are writing a string to a variable that can only hold a single char. Even a single letter guess will require two characters to store as all C strings are NUL terminated.
– kaylum
I am trying to write a program that loops asking the user to continuously input either a float, int, or char and echo it back to them until they enter 'q', then the loop ends. I do not understand how to decipher between an int, char, or float before entering the loop. I have tried if (scanf("%c", ch)) and so on for float and int and that works great, but once I added the loop in it's messing me up. I have tried several different combinations, but I have still not found my answer.
Here is one attempt to show you exactly what I am trying to do:
char ch;
int num = 0;
float fl = 0;
printf("Enter a value: ");
while(ch != 'q') {
if (scanf("%c", &ch) && !isdigit(ch)) {
printf("You entered a character %c\n", ch);
}
else if (scanf("%d", &num)) }
printf("You entered an integer %d\n", num);
}
else if (scanf("%d", &num)) {
printf("You entered a floating point number %f\n", fl);
}
printf("Enter another value: ");
}
}
This keeps doing something strange and I cannot pinpoint my problem. Thank you in advance!
You cannot accomplish that with your approach. You can scan a line and parse it accordingly:
char line[128]; /* Create a buffer to store the line */
char ch = 0;
int num;
float fl; /* Variables to store data in */
int r;
size_t n; /* For checking from `sscanf` */
/* A `do...while` loop is best for your case */
do {
printf("Enter a value: ");
if(fgets(line, sizeof(line), stdin) == NULL) /* If scanning a line failed */
{
fputs("`fgets` failed", stderr);
exit(1); /* Exits the program with a return value `1`; Requires `stdlib.h` */
}
line[strcspn(line, "\n")] = '\0'; /* Replace `\n` with `'\0'` */
r = sscanf(buffer, "%d%zn", &num, &n);
if(r == 1 && n == strlen(line)) { /* If true, entered data is an integer; `strlen` requires `string.h` */
printf("You entered an integer %d\n", num);
}
else{
r = sscanf(buffer, "%f%zn", &fl, &n);
if(r == 1 && n == strlen(line)) { /* If true, entered data is a float; `strlen` requires `string.h` */
printf("You entered a floating point number %f\n", fl);
}
else{
if(strlen(line) == 1) /* If true, entered data is a character; `strlen` requires `string.h` */
{
ch = line[0];
printf("You entered a character %c\n", ch);
}
else{ /* Entered data is something else */
printf("You entered \"%s\"\n", line);
}
}
}
}while(c != 'q');
Disclaimer: I wrote the above code using a mobile and I haven't tested it.
Update (did not test and wrote with my mobile):
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main(void)
{
int c = 0;
bool random = false;
bool flag = true;
bool is_float = false, is_char = false, is_number = false;
do{
c = getchar();
if(c == EOF)
break;
if(!random)
{
if(isdigit(c))
{
is_number = true;
}
else if(c == '.')
{
if(is_number)
{
if(is_float)
{
random = true;
}
else
{
is_float = true;
}
}
else if(!is_number && !is_float && !is_char)
{
is_float = true;
}
}
else if(c == '-' && !is_float && !is_number && !is_char);
else if(isalpha(c))
{
if(is_char)
random = true;
else
{
is_char = true;
if(c == 'q')
flag = false;
}
}
else
{
random = true;
}
if((is_char && is_float) || (is_char && is_number))
random = true;
if(c == '\n' && !is_char && !is_float && !is_number)
random = true;
}
if(c == '\n')
{
if(random)
/* puts("You entered a random string!"); */
puts("Invalid input!");
else if(is_float)
puts("You entered a float!");
else if(is_number)
puts("You entered a number!");
else if(is_char)
puts("You entered a character!");
else
puts("Error!");
if(!flag && !is_number && !is_float && !random)
flag = false;
else
flag = true;
is_char = is_float = is_number = random = false;
}
}while(flag);
puts("Done");
return 0;
}