following problem:
I want to make a kind of hangman game (everything in the console).
so i made a loop which turns 13 times after it runs out, the player loose (it only count down if the player inserts a wrong letter).
now, i want to show the user which letters he allready used. so the output should look like this: "you allready used: a, b, c, g..." and so on. So after every try, the line grow by one letter (the input letter of course).
i tried strcpy, but it only makes random letters which i never put in, and it doesn't grow, so how can i handle this?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <ctype.h>
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
char word[81], used[14];
int wrong=0, laenge, _, i;
char input;
SetConsoleTitle(" Guess me if u Can! ");
//printf("\n\n spielst du mit einem Freund oder alleine?"); /*for later
//printf(" \n\n [1] alleine"
// " \n\n [2] mit einem Freund"); */
printf("\n\n please insert a word (max. 80 characters): \n\n");
gets(word);
laenge=strlen(word);
printf("\n\n this word has %i characters.\n\n",laenge);
for(i=0; i<13; i++)
{
// for(_=0; _<laenge; _++) /*ignore this this is also for later
// printf(" _");
// printf("\n"); */
gotoxy(10,10);
printf("\n\n please insert a letter now: ");
input=getch();
strcpy(used, &input);
printf("\n\n The following characters are allready used: %c ", used);
if(strchr(word, input)){
printf("\n\n %c is in the word\t\t\t\t\t\t\n\n");
i--;
}
else{
printf("\n\n the letter %c is wrong!\n");
wrong++;
printf(" you have %i try",13-wrong);
}
}
system("cls");
printf("\n\n to many tries.\n\n");
system("Pause");
}
First, you should fill up used with 0 characters to ensure it is always properly terminated:
memset(used, 0, 14);
Then, add a new character to it like this:
used[i] = input;
Also, as #Fred noted, you should use the proper format specifier %s in the printf call.
As already said here you should fill used with zeros, something like used[14] = {0};
Then I think the line printf("\n\n The following characters are allready used: %c ", used); should be printf("\n\n The following characters are allready used: %s ", used);, notice the "%s" you're printing a string.
If you know the maximum size, you can create a buffer with that maximum size, and then append to it. In this case you do know the maximum size, as there are only 26 letters in the alphabet. So the maximum length of the string is the length of whatever text you put at the beginning, plus 26 times the number of characters you'll use for each letter. I count 18 in the initial string. Remember to add one for the null byte terminator at the end. For each letter you have the letter, a comma, and a space, so the max length is 18 + 26*3 + 1 = 97 if I did the arithmetic right.
So you could write something like:
char used[96];
strcpy(used,"You already used: ");
int first=TRUE;
... whatever other work ...
... let's say we get the character in variable "c" ...
// Add comma after previous entry, but only if not first
if (!first)
{
first=FALSE;
strcat(used,", ");
}
// turn character into a string
char usedchar[2];
usedchar[0]=c;
usedchar[1]='\0';
// Append to working string
strcat(used,usedchar);
Related
Acc. to this post, the most used method to store text in a 2D array is by using %s approach. But, this approach has a downfall, i.e. whenever you press spacebar, the text which is typed after goes into the second element of array. for e.g. you typed
Input:-
1st element of char array = Hi everyone
Output:-
1st element of char array = Hi
2nd element of char array = everyone
Expected output:-
1st element of char array = Hi everyone
So, i want to ask why the below written approach cannot be used to enter text into a 2D array?
#include <stdio.h>
int main()
{
char ch[20];
printf("Enter name:");
scanf("%19[^\n]", ch);
printf("Your name is: %s", ch);
return 0;
}
If the above approach can be used, then please let me know how?
Please do not introduce pointer concepts/code in answer to this post. This is a question to understand why the above written approach fails.
Consider this as the code which fails:-
#include <stdio.h>
int main()
{
char name[4][20];
int i;
printf("Enter names:-\n");
for(i=0; i<4; i++)
{
printf("Enter name %d: ", i);
scanf("%19[^\n]", name[i]);
printf("\n");
}
for(i=0; i<4; i++)
{
printf("Entered name %d: %s", i, name[i]);
printf("\n");
}
return 0;
}
The above program compiles without any error or warning, but fails during runtime.
The problem in the example you provided is that the newline is left in the buffer. You can discard this leading whitespace by changing this:
scanf("%19[^\n]", &name[i]);
To this
scanf(" %19[^\n]", &name[i]);
Note the space before %19. With this, your program prints:
Enter names:-
Enter name 0: foo
Enter name 1: bar
Enter name 2: baz
Enter name 3: qux
Entered name 0: foo
Entered name 1: bar
Entered name 2: baz
Entered name 3: qux
This is because the %[^\n] specifier tells it to take everything but the newline. So the newline will be left in the buffer, and when scanf is called again, it is the first thing in the buffer, so those additional calls can't take any input.
That leading space in the scanf fixes the problem, because it tells scanf to discard any trailing whitespace, which includes that newline left in the buffer.
This is what a reference says about it:
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace
character (whitespace characters include spaces, newline and tab
characters -- see isspace). A single whitespace in the format string
validates any quantity of whitespace characters extracted from the
stream (including none).
Figured out another approach to get it done.
#include <stdio.h>
int main()
{
char name[4][20];
int i;
printf("Enter names:-\n");
for(i=0; i<4; i++)
{
printf("Enter name %d: ", i);
scanf("%19[^\n]", name[i]);
fflush(stdin);
printf("\n");
}
for(i=0; i<4; i++)
{
printf("Entered name %d: %s", i, name[i]);
printf("\n");
}
return 0;
}
So I'm doing this problem where I need to calculate the average using pointers and without using strings. The user will input a letter and then a space followed by a number(an integer), the letter indicating if the number is positive(p) or negative(n) or if the user is done input-ing numbers(e).
I know I need a loop to continually read in number and add or subtract them from the sum until the letter "e" is input.
program should have and use the following function
// Precondition: value will be a pointer to where the input value is to be stored.
// Postcondition: returns true if a number was read, or false if
// it was the end of the list. The int pointed to by value will be
// set to the number input by this function, made negative or
// positive depending on the character before it. int read_number(int* value)Íž
A sample input being p 20 p 20 p 10 p 10 e
output: 15
My problem as of now is my loop is only reading for two cycles of input, and even then it isn't printing the average. Also I'm supposed to use a pointer but given the directions i'm still not sure what the context is, I'm not seeing where a pointer is useful.
#include <stdio.h>
//precondition: value will be a pointer to where the input value is to be stored.
int main(){
int sum;
int num;
int counter;
float avg;
char let;
scanf("%c %d", &let, &num);
for (counter=0;let == 'n' || let == 'p'; counter++){
scanf("%c %d", &let, &num);
if ( let == 'n'){
sum-=num;
}
if (let == 'p'){
sum+=num;
}
if ( let == 'e'){
avg=sum/counter;
printf("%f", &avg);
}
}
return 0;
}
Your input is:p 20 p 20 p 10 p
10 e.
The scanf before the loop scans 'p' and then skips the space and then scans 20. The next scanf in the loop reads the space as it is also a character and the %d fails to scan an int and the stops scanning. See the problem?
To fix it, change
scanf("%c %d", &let, &num);
To
scanf(" %c %d", &let, &num);//Note the space before %c
The space before %c gobbles up whitespace characters(if any) like newlines, spaces etc until the first non whitespace character.
Other problems include not initializing sum to 0 and using &avg instead of avg in the printf below
printf("%f", &avg);
I have to take input in the following format
S1 S2 S3
where S1 is a character and S2,S3 are integers
for example
3
A 123 452
D 450 53
B 330 672
(where the '3' represents the number of queries)
Now I've written the following code for it :
while(i<=Q){
scanf("%c %d %d",&ch,&index,&num);
printf("%c %d %d\n",ch,index,num);
i++;
}
However, for the above shown three values I am getting the following output
0 755130840
A 123 452
123 452
with an extra line at the top and that large value (here 755130840) changing every time.
Where am I going wrong?? I even tried scanning the 3 values individually and flushing the input stream before each scan statement. However, It doesn't help either.
Given the two blank lines, I believe the newline ('\n') is being stored in some variable.How do I handle it?
Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading ch.
scanf with blank skips white space (including newlines) and reads the next character that is not white space.
Here is a code , this would be working fine.
#include <stdio.h>
int main(void) {
// your code goes here
int i =0;
int Q = 2;
char ch;
int index;
int num;
while(i<=Q){
scanf(" %c %d %d",&ch,&index,&num);
printf("%c %d %d\n",ch,index,num);
i++;
}
return 0;
}
do you want something like this?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, count, numone, numtwo;
char charip;
printf("Enter numbr of elem:\t");
scanf("%d", &num);
if (num < 0)
{
printf("Enter positive value!!!!!\n");
exit (-1);
}
count = 0;
while (count < num)
{
getchar();
scanf ("%c %d %d", &charip, &numone, &numtwo) ;
printf("%c %d %d\n", charip, numone, numtwo);
count++;
}
return 0;
}
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.
Basically I have a C program where the user inputs a number (eg. 4). What that is defining is the number of integers that will go into an array (maximum of 10). However I want the user to be able to input them as "1 5 2 6" (for example). I.e. as a white space delimited list.
So far:
#include<stdio.h>;
int main()
{
int no, *noArray[10];
printf("Enter no. of variables for array");
scanf("%d", &no);
printf("Enter the %d values of the array", no);
//this is where I want the scanf to be generated automatically. eg:
scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);
return 0;
}
Not sure how I might do this?
Thanks
scanf automatically consumes any whitespace that comes before the format specifier/percentage sign (except in the case of %c, which consumes one character at a time, including whitespace). This means that a line like:
scanf("%d", &no);
actually reads and ignores all the whitespace before the integer you want to read. So you can easily read an arbitrary number of integers separated by whitespace using a for loop:
for(int i = 0; i < no; i++) {
scanf("%d", &noArray[i]);
}
Note that noArray should be an array of ints and you need to pass the address of each element to scanf, as mentioned above. Also you shouldn't have a semicolon after your #include statement. The compiler should give you a warning if not an error for that.
#include <stdio.h>
int main(int argc,char *argv[])
{
int no,noArray[10];
int i = 0;
scanf("%d",&no);
while(no > 10)
{
printf("The no must be smaller than 10,please input again\n");
scanf("%d",&no);
}
for(i = 0;i < no;i++)
{
scanf("%d",&noArray[i]);
}
return 0;
}
You can try it like this.