#include <stdio.h>
#include <conio.h>
#define max 100
void compare(char *name,char* input);
int main()
{
int i=0;
char name[max]="santosh";
char input[max];
printf("enter the password\n");
while((input[i]=getchar())!='\n'){
i++;
}
input[i]='\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while((*name==*input)&&(*name!='\0'&&*input != '\0')){
*name++;
*input++;
}
if(*name=='\0'&&*input=='\0')
printf("Correct Password");
else
printf("Incorrect Password");
}
This Program is getting crashed in vs code but when I use getchar() instead of getch() or getche() all is working fine.
Why it is not working with getch() and how it will run as I want user to insert a password and thus want to use getch() not getchar().
First of all #define max generates a warning "macro redefinition", so change that.
The second problem is that getch() and getche do not convert the Enter key to 'newline' \n but to 'return' \r
The third problem is that instead of incrementing the pointers, you are incrementing what they point to.
Here is the corrected code:
#include <stdio.h>
#include <conio.h>
#define MAXX 100 // fixed macro name collision
void compare(char *name, char* input);
int main(void) // corrected definition
{
int i = 0;
char name[MAXX] = "santosh";
char input[MAXX];
printf("enter the password\n");
while((input[i] = getche()) != '\r') { // fixed '\n' check
i++;
}
input[i] = '\0';
compare(name, input);
return 0;
}
void compare(char *name,char* input){
while(*name == *input && *name != '\0' && *input != '\0') {
name++; // fixed pointer increment
input++; // fixed pointer increment
}
if(*name == '\0' && *input == '\0')
printf("Correct Password\n");
else
printf("Incorrect Password\n");
}
Finally you should also check i does not exceed the array bounds. The strings seem long enough, but not for players who try to break the program.
Related
I'm making a function to validate an integer within a domain and ask the user to type again if the number is out of range or if they typed in a character(or string of characters) or if they typed in more than just an integer. The code looks like this:
#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
//\input stream clear function\*
void clear()
{
char c;
while((c=getchar())!='\n'&&(c=getchar())!=EOF){}
}
//getchar(char str[], min, max)
int GetInt(char msg[], int min, int max)
{
int value;
int rc;
char ovflow;
while (true)
{
printf("%s", msg);
rc = scanf("%d%c",&value,&ovflow);
if(rc == 0 || rc == 1)
{
printf("**No input accepted!**\n\n");
clear();
}
else if(ovflow != '\n')
{
printf("**Trailing characters!**\n\n");
clear();
}
else if(value < min || value > max)
{
printf("**Out of range!**\n\n");
}
else break;
}
return value;
}
int main()
{
int value=GetInt("enter value: ",2,20);
return 0;
}
Things work fine but when I typed in "something", the program froze until I press another Enter. It should look like this:
It froze if I typed in some certain string
It should still print the printf("%s", msg); and immediately prompt for more input. I could guess it was because of clear() function but whatever I tried, I could not fix it. I would be thankful if you can help me with this.
The answer is to just call getchar() once. ex:
((c = getchar()) != '\n' && c != EOF) {}
From a comment by Johnny Mopp
This a reverse string code but the loop cant be terminated and keeps taking input
How can I terminate it
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i;
do {
gets(str);
for (i = (strlen(str) - 1); i > -1; i--) {
printf("%c", str[i]);
}
printf("\n");
} while (str[0] != '\0');
return 0;
add str[0]='\0'; before gets and its done. this is because making a loop termination and to get out of the loop after clicking enter.
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i,lenh;
do{
str[0]='\0';
gets(str);
lenh=strlen(str);
for(i=lenh-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
}while(str[0]!='\0');
return 0;
}
now, there are a few points (answer code below)
Basically, you are printing hand-to-hand with input, while the question states of a multi line input. So, first you have to take all the inputs and then output will be shown.
Your original code does not keep taking input as you have said. Question says the last string is empty string. You press enter in empty string, your above code will terminate.
Remember Last Input String Should be Empty, that's termination condition
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char stringArray[50][100]={0};
int k,m,count=0,i=0,j=0;
do {
fgets(str,100,stdin);
k=strlen(str);
for(m=0;m<k-1;m++){
stringArray[count][k-m-2]=str[m];
}
count++;
}
while (str[0] != '\n');
for(i=0; i<count; i++){
for(j=0;stringArray[i][j]!=0;j++){
printf("%c",stringArray[i][j]);
}
if(i<count-1){
printf("\n");}
}
return 0;
}
sample input
Hello team Loop
Welcome
sample output
pooL maet olleH
emocleW
My code seems fine, but I get this warning (warning: comparison between pointer and integer), what is the best solution to solve this problem?
I have already used double notation marks for (char exit = "E"), also used the same thing with while but the same problem.
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while (c != exit)
{
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
}
}
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while (c != exit) // here ...
{
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
}
}
you are trying to compare a char to the pointer the array c decays to. What you perhaps wanted to do is to compare the first character of the array to the character exit:
while (c[0] != exit)
But that still doesn't make much sense since c is uninitialized and the user not yet had a chance to make any input. Better use a do ... while-loop:
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
do {
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
} while (c[0] != exit);
}
Next thing is, that scanf("%s", c); could fail (yes unlikely, but possible). And the user could enter more characters than there is room for in the array c. You should never use scanf() whithout checking the return value nor "%s" without specifying a WIDTH for the conversion specifier to limit the characters put into the array.
When reading a string you need memory for WIDTH characters + a terminating '\0'. So if you want to read a string of one character, the array has to have at least 2 elements:
#include <stdlib.h
#include <stdio.h>
int main()
{
char c[2];
char exit = 'E';
do {
printf("Enter a character\n\n");
while (scanf("%1s", c) != 1 ) {
fputs("Input error!\n");
return EXIT_FAILURE;
}
printf("your character is : %s\n-------------------\n", c);
} while (c[0] != exit);
}
But if you only want to read one character you are better off with getchar():
#include <stdio.h>
{
int ch;
while (printf("Enter a character\n\n"),
(ch = getchar()) != EOF && ch != 'E')
{
printf("your character is: %c\n-------------------\n", (char) ch);
}
}
i believe this is what you are trying to do.
warning is because you have not initialzed your character and also you were comparing address of character to character value.
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while ((c[0]=getchar()) != exit)
{
if(c[0]==EOF)break;
printf("your character is : %c\n",c[0]) ;
}
printf("ended");
}
I currently have a homework assignment and I used gets.
The professor said I should be using getchar instead.
What is the difference?
How would I change my code to use getchar? I can't seem to get it right.
code:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
int main() {
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1) break;
}
}
int getword(char *w) {
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n"); //user input
gets(str);
for(i = 0; str[i] != '\0' && str[i] !=EOF; i++){
if(str[i] != ' '){
charCount++;
} else {
str[i] = '\0'; //Terminate str
i = -1; //idk what this is even doing?
break; //Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount); //output
strcpy(w, str);
// return charCount;
return strlen(w); //not sure what i should be returning.... they both work
}
gets() was supposed to get a string from the input and store it into the supplied argument. However, due to lack of preliminary validation on the input length, it is vulnerable to buffer overflow.
A better choice is fgets().
However, coming to the usage of getchar() part, it reads one char at a time. So basically, you have to keep reading from the standard input one by one, using a loop, until you reach a newline (or EOF) which marks the end of expected input.
As you read a character (with optional validation), you can keep on storing them in str so that, when the input loop ends, you have the input string ready in str.
Don't forget to null terminate str, just in case.
what i want to do is take a big input(read till users press enter(\n) ) and then call a function that puts the first word of this input(read till ' '). My problem is that even though it looks pretty simple it also has 2 extra allien characters in it. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void findChoise(char *input, char *choise);
int main()
{
char choise[12];
char input[300];
printf("give me the input: ");
gets(input);
printf("%s\n", input);
printf("%s%d\n", "length of input: ", strlen(input));//for checking
findChoise(input, choise);
printf("%s%d\n", "length of output: ", strlen(choise));//for checking
printf("%s\n", choise);
return 0;
}
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
};
}
What you have already done is very close. You are just missing the null character at the end of the string ("\0"). I have cleaned up your code a little bit and fixed somethings. Please read through it and try and understand what is going on.
Main things to note:
All strings are arrays of characters and terminates with a null character "\0"
When you declare buffers(input and choice), try to make them a power of 2. This has to due with how they are stored in memory
Avoid using gets and try scanf instead
#include <cstdio>
void findChoice(char*, char*);
int main() {
char choice[16];
char input[512];
scanf("%s", input);
findChoice(choice, input);
printf("%s", choice);
return 0;
}
void findChoice(char* input, char* choice) {
int i = 0;
while(input[i] != ' ') {
choice[i] = input[i];
++i;
}
choice[i] = '\0';
}
You also need to write a null character to end the choise string:
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
}
choise[i] = 0;
}
also don't use gets:
fgets(input, sizeof(input), stdin);
and use %zu to print size_t:
printf("%s%zu\n", "length of input: ", strlen(input));