Pointers to Array Elements in C - c

I am trying to create a program that prints a random number whenever the user enters "roll", and allows the user to enter "1" if the random number is greater than or equal to 3.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int randomnumber;
char diceinput;
int slotnumber;
char lettertable[7];
char *character;
lettertable[1] = 'l';
lettertable[2] = 'r';
lettertable[3] = 't';
lettertable[4] = 'e';
lettertable[5] = 't';
lettertable[6] = 'e';
character = &lettertable[1];
printf("Enter 'roll' to roll the dice. Enter 'exit' to quit.\n");
scanf("%s", &diceinput);
if (strcmp(&diceinput, "exit")==0) {
printf("Now quitting. Thank you, and please play again!\n");
}
if (strcmp(&diceinput, "roll")==0) {
srand((unsigned)time(NULL));
randomnumber = rand() % 6 + 1;
printf("%d\n", randomnumber);
if (randomnumber >= 3) {
printf("Enter 1 to get the corresponding letter from table.\n");
scanf("%d", &slotnumber);
if (slotnumber == 1) {
printf("%s", character);
}
}
}
}
After the user enters "1" the program is supposed to get the letter stored in the letter table[1], an element in the array lettertable. However, when I run the program and enter "1", instead of getting the letter "l", the output is a weird phrase: "lrtete" with an upside down question mark. Can somebody please help me? Thank you.
Please note that the code shown above is only a revelant section of the unfinished program.

Try this
if (slotnumber == 1)
{
printf("%c", *character);
}
Also as pointed by Jonathan Leffler your code does not quit for if (strcmp(&diceinput, "exit")==0). You should use exit(0) to quit;
if (strcmp(&diceinput, "exit")==0)
{
printf("Now quitting. Thank you, and please play again!\n");
exit(0);
}

if you're trying to output one letter try replacing printf("%s" , character) with printf("%c" , *character)

Use %c as in printf("%c", *character); instead of %s in printf("%s", character);
You have a few logical mistakes in your code:
1) char diceinput; and then scanf("%s", &diceinput);, this is a big mistake, your program may crash as you don't have sufficient memory allocated (neither statically nor dynamically) for the input string. Use char diceinput[5]; and scanf("%s", diceinput);
2) You have started indexing from 1. (Pardon me if its intentional)
3) You are using printf("%s", character);, I will say its your luck that you are getting "lrtete" as output, i.e. it may not stop at ..te and print some garbage characters after, because there is no explicit \0 character at the end of character array.

The printf function will print what it finds at the location provided and will stop printing when it finds a binary zero. Your problem is here:
printf("%s", character);
Since the second element of the array is not zero it will keep printing until it happens to find a zero. In your case you were lucky and it found one before printing lots of garbage.

Related

C guessing game using while loops to limit user guesses and isdigit for verification

Task:
Create a number guessing game where the user has a limited number of guesses to figure out what the randomly generated number is
Check whether the user has inputted a digit or character using "Isdigit" informing them to input a number between 1 and 20 if they use the wrong input or guess out of the expected range.
Using a while loop limits the user guesses
After the user runs out of guesses close the program
Problem I'm facing: I'm new to programming and so I don't have too much experience yet. It's my first time trying to understand the is digit function and I feel like there is a more efficient way of solving this problem.
Since I'm using 2 data types when trying to compare int's and chars I can't make a direct comparison but I figured out the difference between char 1 and int 1 is 48 apart so I made that as a temporary solution. But it only works for single-digit numbers
I've read that I might be able to go through the string character by character to make sure each of them are a digit before the input is accepted and combine the string at the end but I'm not sure how to do that
The user can't input more than 1 character or the program ends
I'd also like to fix any other bugs people may find and write the code in a more effective and understandable way
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main()
{
int iRandomNum = 5; //setting up a number as a placeholder until Code works
char guess; //char being used as I beleive it needs to be char for isdigit to function
int guessCount = 0; //
int guessLimit = 3;
int outOfGuess = 0;
srand(1-10);
//iRandomNum = (rand()%20)+1;
while (guess != iRandomNum && guessCount != 3 && outOfGuess == 0){ //Intended to break out of loop once any variable is satisfied
if(guessCount< guessLimit){
printf("\n%d", iRandomNum);
printf("\nYou have %d guesses left", guessLimit- guessCount); //extra user info
printf("\nGuess the number between 1 - 10: ");
scanf(" %s", &guess);
if (isdigit(guess)==0)
{
printf("\nEnter a digit!");
guessCount++; //supposed to limit user to 3 chances
}else
{ //need help solving this
printf("\nYou entered %d\n", guess - 48); //Using for testing
guess = guess - 48;
if (guess == iRandomNum) //I dont think functions as char and int are different data types
{
printf("\nYou've Won");
break;
}else{
printf("\nWrong guess");
guessCount++;
}
}
}else //Once user runs out of guesses while loop should break an then display following data
{
printf("Second else");
guessCount++;
//outOfGuess = 1;
}
}
if (outOfGuess == 1){
printf("\nOut of guesses!");
}
else{
printf("\nCongratulations!");
}
return 0;
}
An issue not already mentioned in comments: guess is used in the while condition before it has been assigned a value - that's an error.
Regarding the main problem:
In order to allow the user to input more than 1 character (i. e. up to two for a two-digit number), you can use a sufficiently sized character array. Of course you then have to account for a second character when checking using "Isdigit". So e. g. replace
scanf(" %s", &guess);
if (isdigit(guess)==0)
with
char s[2+1]; // +1 for string-terminating null character
if (scanf(" %2s", s) < 1 || !isdigit(s[0]) || s[1] && !isdigit(s[1]))
In order to convert the string in the array to an integer, you can simply use atoi:
guess = atoi(s);

How I print the input character?

Hey I am beginner in programming i need help to solve this problem
I want that i input some character and i want to print it..
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
return 0;
}
From the above code I am not getting any output i also try using loop but not get any result please help me what is correct program so that if i enter any string i print on the screen?
So here's your issue.
You are defining an array of type char with a length of 50. You then read from stdin a string, and then store it at the address of the 50th element. So what will happen is you are storing the string "out of bounds" and you may get a crash, or may not.
Either way, something very bad is happening. You are writing data to an area of memory that you should not be.
So what you want to do is write that data to the address of the 0th index of the array.
You do that by using &a[0] or, for simplicity's sake: a. Both mean the same thing.
At the end of the day, what you want is this:
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",a);
printf("You entered is %s",a);
return 0;
}
I understand you are a beginner and are learning basic concepts, but keep in mind, this code is very unsafe. Because if someone types in a length of characters longer than 50, you are back in the same boat you were before.
Quoting kaylum's comment, "It would be beneficial to go through a basic C book or tutorial before proceeding further."
Now about your issue, change these lines:
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
to
scanf("%50s", a);
printf("You entered \"%s\".\n", a);
If you just want to print what's inputted by the user then you could use buffer:
#include <stdio.h>
int main(void)
{
char c;
printf("Enter the string(~ to exit)\n");
while((c = getchar()) != '~')
putchar(c);
return 0;
}
Output:
Enter the string(~ to exit)
This is a test program // press enter
This is a test program // same output
~ // exit

Palindrome in C using scanf and no string library functions

the assignment is to get an input string, and using no string library functions to be able to handle the string. this code at the moment doesn't even print out the string i get in. when I remove the functions from main it magically starts to print. any help would be greatly appreciated
#include <stdio.h>
#include <string.h>
#define SIZE 32
int isQuit(char str[]);
void isPalindrome(char str[]);
int main (){
int cont = 0;
char str[SIZE];
fflush(stdin);
printf("please enter a word:\n");
scanf("%s\n", str);
printf("%s\n", str);
while(cont == 0)
{
scanf("%s\n", str);
printf("%s\n", str);
cont = isQuit(str);
isPalindrome(str);
}
return 0;
}
You most likely are suffering from line buffering in your terminal. Until you write a newline character, any characters written are not displayed.
Try adding a newline when displaying your input:
printf("%s\n", str);
The same goes for any other printf calls you do that you want to ensure are displayed.
By the way, your null-termination test is incorrect. The escape character is \, not /. Change your loop to:
while (str[h] != '\0')
Or simply:
while (str[h])
There are a few things wrong with your code here:
while(isQuit(str) == 0)
{
isPalindrome(str);
return 0 ;
}
Since you have the return keyword in your loop body (unconditionally), the loop will execute at most one time.
Also, neither isQuit nor isPalindrome take input from the user. This means that even if you were to fix the loop by removing the return statement, it still wouldn't be right; you'd have an infinite loop of isQuit and isPalindrome being passed the same str that the user got asked for on line 15.
What you have to do is change your while loop to continually poll the user for input and act upon it, in addition to the issues pointed out in #paddy's answer.

Query user to continue printing in C

I am writing a program that starts printing at 0.
It prints up to 15 and asks the user a y/n question.
if y that program prints next 15.
if n program stops.
The program I wrote does not work.
Help solving this.
int main()
{
int i=0,k=1;
char ans;
while(k=1)
{
i++;
printf("\n%d",i);
if(i%15==0)
{
printf("\nDo you want to continue?(y/n): ");
scanf("%c",ans);
ans = toupper(ans);
if(ans=='Y') {
continue;
}
else if(ans=='N') {
k=0;
}
}
}
}
----------------------------------EDIT-------------------------------------
changed the code as #Programmer400. Also 15-->3. Now my computer prints
1
2
3
Do you want to continue?(y/n): y
4
5
6
Do you want to continue?(y/n):
7
8
9
Do you want to continue?(y/n): y
First it prints till 3 and asks. After Y, it prints till 6 and asks and then without any input prints till 9 and asks. Note the missing y in the 2nd question.
I have provided a working C program below that performs the tasks you specified in your question.
I have taken an effort to stay true to the functions that you used in your original code sample and I have also taken care to only make additions (not remove code).
In the comments, I have explained lines of code that I have added that were not in your original code sample.
#include <stdio.h>
int main(void)
{
int i = 0, k = 1;
char user_input;
char ans;
while(k == 1)
{
i++;
printf("%d\n", i);
if (i % 15 == 0)
{
printf("Do you want to continue? (y/n/Y/N): ");
scanf(" %c",&user_input); // Keep the whitespace in front of the %c format specifier -- it's important!
getchar(); // Consume the newline character left in the buffer by scanf()
// Check if user input is already capitalized
if (user_input >= 65 && user_input <= 90)
// If it is, keep it capitalized
ans = user_input;
else
// If it isn't, capitalize it
ans = toupper(user_input);
if (ans=='Y')
{
// Allow the loop to continue
continue;
}
else if (ans == 'N')
{
// Inform the user that execution is ending
printf("Exiting loop... ending program.\n");
// Consider removing 'k' entirely, just use a 'break' statement
k = 0;
}
else
{
// Inform the user that the input was not recognized (if not y/n/Y/N...)
printf("User input not recognized... please provide input again.\n");
// Decrement 'i' so that the user is forced to provide input again...
i--;
// Allow the loop to continue
continue;
}
}
}
}
Helpful notes:
scanf leaves a newline character in the buffer when you are reading user input with character formatters. Namely...
%c, %n, and %[] are the 3 specified expectations that do not consume leading whitespace
-- From a comment on this StackOverflow answer.
Keep in mind that if you would like to exit your while loop, you could simply insert a break statement. This way, you don't have to change the value of k (which is rather ambiguous) to end the loop and the code is more readable because an explicit break statement is harder to misinterpret. In this simple case, the use of k is easily understood (so don't worry about it too much, for now).
If you ever intend to read string input from a user (i.e., an array of characters), then I would recommend that you use fgets() instead of scanf(). A discussion of the merits of fgets() in comparison to scanf() is provided in this StackOverflow answer. Further, it is important to recognize that even though you can use gets() to perform a similar operation it is highly dangerous and never advised. Check out the explanations provided by the top two answers to this StackOverflow question.
I tried changing your code so that it doesn't generate warnings, now it seems to "work" (but maybe it can be even more correct).
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
int main()
{
int i=0,k=1;;
char c;
char ans[] = "";
while(k==1)
{
i++;
printf("\n%d",i);
if(i%15==0)
{
printf("\nDo you want to continue?(y/n): ");
scanf(" %c",ans);
ans[0] = (char) toupper(ans[0]);
if(ans[0]=='Y') {
continue;
}
else if(ans[0]=='N') {
k=0;
}
}
}
}

C: Count letters until specific entry inserted

I'm a bit rusty on C. I'm in a school assignment that is asking me to make a program that gets user input, following that print the output. If the character count is higher than 50, to not print anything out and reprompt them. Quit should not print a count (in this case, 4).
This is what I have so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{ /*Start of main*/
printf("Type any word you'd like <= 50 characters.\nType quit to exit:\n");
char word[50];
int wordLength = 0;
while (strcmp(word, "quit") != 0)
{/*open of while loop (strcmp ... != 0)*/
scanf("%s\n", word);
wordLength = strlen(word);
if (wordLength > 50)
{
printf("Try again, >= 50 characters!:\n");
scanf("%s", word);
wordLength = strlen(word);
}
printf("%d\n", wordLength);
}/*End of while loop (strcmp... != 0)*/
return 0;
}/*End of main*/
I can't seem to get the length immediately following the submitted word. It appears to get wonky. It shows the number for the LAST submittted word after putting in a new word. It doesn't matter where I put the printf, it takes its time.
Can someone explain to me why it's so slow, and suggest a method I could implement to make it faster? This is a school assignment, please don't share direct answers, but guide me into the way I should be thinking? :)
I'm almost thinking this is inefficient coding with the delay.
You're all life savers!!!
Remove \n from first scanf()
scanf("%s\n", word);
#---------^
Thanks to #remyable, \n has different meaning in scanf() - not the one you are expecting here to read newline. Refer C-faq 12.17
Also, checking for input for more than 50 chars that is not correct. You would get into buffer overrun. Look for different way to limit that.
The code has multiple problems
the while statement is using word before word is initialized
the scanf doesn't limit the number of characters that get written
into word
strlen can only return a number >50 if you overran the buffer
the code only reprompts once, it should reprompt until the user gets it right

Resources