blanking a char variable in c - c

I have declared a char variable ope in function main.
i took the input through getchar function and stored in ope.
Now i want to blank the variable so i will be able to store some other in ope.
Can anybody show me how to do it??
I just want to continuously store the input in ope variable. If it's possible through some other way, kindly guide me. I will be very thankful.

You can reuse the getchar() function same way you used it first time.
Here is sample code from the cplusplus.
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}

You don't need to blank it, just do getchar() once again.
Eventualy set it to or "0 char"
c = '\0'; or c = 0;

Related

Is there any function in C to replace getch() for my given program as it a non-standard function?

I want and searching for a function or an alternative that could replace the non-standard getch() function of C language. I want help if any any function which can replace the getch() function from the code below or an appropriate alternative.
I am doing this since my college has asked me not to use the conio.h header file in my C programs.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int i=0, j=0, memAlloc=1;
char *p, *q, a;
p=(char *)calloc(1, sizeof(char));
while(1)
{
a=getch(); //getch() function
if(a!='\b'&&a!='\r')
{
p[i]=a;
++i;
printf("%c", a);
memAlloc++;
p=realloc(p, memAlloc*sizeof(char));
}
if(a=='\b'&&i>=1)
{
printf("\b \b");
--i;
}
if(a=='\r')
{
p[i]='\0';
break;
}
}
printf("\n");
for (i=0; p[i]!='\0'; i++)
printf("%c", p[i]);
//Storing a string of only alphabets into a new dynamic array
q=(char *)calloc(1, sizeof(char));
memAlloc=1;
for (i=0; p[i]!='\0'; i++)
{
if (isalpha(p[I])) //Checking for alphabet
if(isupper(p[i]))
{
q[j]=p[i]+32; //If uppercase alphabet convert it to lowercase
memAlloc++;
q=realloc(q, memAlloc*sizeof(char));
j++;
}
else
{
q[j]=p[i];
memAlloc++;
q=realloc(q, memAlloc*sizeof(char));
j++;
}
}
q[j]='\0'; //Adding a null character to the end of the string
free(p);
printf("\n");
for (i=0; q[i]!='\0'; i++)
printf("%c", q[i]);
}
Here is the explanation of the program.
The program will take a string input from the user of unknown size and save it to the dynamic array. The user will keep on entering characters in a single line until he presses the enter key after which the whole string is saved to a dynamic array. The program then removes every character except alphabets and converting uppercase alphabets to it's lowercase and then saves the updated string to an another dynamic array.
try this scanf(" %c",&a);
also you can use getchar() but note that both of these functions(scanf and getchar()) will leave a \n in buffer and so in your next enter to loop , they will take that as input ,which means you can use two getchar() , or add a space in scanf like above.
as I see your code , you only want one character and no white-spaces which means you use scanf like above and that white space will be ignored.
If you can live with that the function will wait until it finds a newline or other whitespace character in stdin - the user needs to input more characters such as the newline made by the press to Return/ Enter - (contrary to the getch() function which does not wait for further input) you can use scanf() or getchar() (both header stdio.h) to get a single character from stdin:
a = getchar();
or
scanf("%c",&a);
Note, that in the case of getchar(), a shall be of type int instead of type char to catch the potential EOF which is returned by an error.
If you´re looking for a standard library function which does not wait for another character in stdin (unless it hasn´t encountered EOF) like getch(), the simple answer is:
There is no one. There are platform-dependent solutions only, like getch() for Windows and DOS is, but not a general standard one for all environments.
You can also use system command to control the terminal in linux like this:
char getch() {
char c;
system("stty raw -echo");
c = getchar();
system("stty -raw echo");
return c;
}
This function does not require the user to press enter and takes input from the user without echoing.
It requires you to add stdlib.h library to your code
Note: This function is only applicable to UNIX-based OS

getchar/putchar returns boxes with question marks when printing inputted characters

Playing around with code examples from K&R in Codeblocks on Windows 10 (Danish language). The following example works as expected:
#include <stdio.h>
int main() {
char c = 'a';
putchar(c);
}
However, the following prints a series of boxes with question marks, the same number as the number of characters I type:
#include <stdio.h>
int main() {
char c;
while (c = getchar() != '\n') {
putchar(c);
}
}
So it looks like an encoding issue. When run, a command prompt opens with "C:\Users\username\Desktop\filename.exe" in the header, and my username contains the Danish character "å" which is replaced by a "Õ". The command prompt uses the CP 850 character set.
(By the way, I'm not checking if the character equals EOF, since that produces odd results. Pressing enter prints the expected number of boxes, plus one for \n, but it doesn't end the program.)
You are seeing a problem of operator precedence here. As you can see on this chart, = has a lower precedence than !=.
This means that getchar() != '\n' is evaluated first.
To the compiler your code looks like this:
#include <stdio.h>
int main() {
char c;
while (c = (getchar() != '\n')) {
putchar(c);
}
}
Since 'c' is getting an incorrect value (the true/false evaluation of the expression), the output is incorrect, and the program gives the behavior you are seeing, however
#include <stdio.h>
int main() {
char c;
while ((c = getchar()) != '\n') { //<----notice brackets around c=getchar
putchar(c);
}
}
gives the output you are expecting. This illustrates the fact that you should always put brackets around such expressions to be safe.
This line is bad.
while (c = getchar() != '\n')
It should be:
while ((c = getchar()) != '\n')
There are already some correct answers within the scope of the question but there are a couple of wider problems that you need to address.
Firstly getchar() returns an int and it is important that you define the variable that takes the return value as an int so you can differentiate errors and end of file from valid chars.
Secondly, if you receive end of file or there is an error on stdin before the program encounters a \n, your code will loop forever. This is what the man page on my laptop says about getchar()
If successful, these routines return the next requested object from the stream. Character values are returned as an unsigned char converted to an int. If the stream is at end-of-file or a read error occurs, the routines return EOF.
So once getchar() returns EOF it will return EOF all the time. You need to address this in your loop condition:
#include <stdio.h>
int main()
{
int c; // c declared as int
while ((c = getchar()) != EOF && c != '\n'))
{
putchar(c);
}
if (c == EOF)
{
// handle errors and end of file as you see fit
}
}
Edit: You get the boxes because of the lack of parenthesis around the assignment, look at this question for reference as to why you should have parenthesis around an assignment used as a truth value...
Also, there is something else that is also wrong with this program, consider this example:-
For example:
What you actually wanted:-
ABCD
< newline >
What you actually typed:-
ABCD
And since the program didn't find the '\n' anywhere in the code, it leads to undefined behavior since it goes out of bounds to find it...
There are two possible solutions when your input does not contain a '\n':-
Use EOF (Suggested by many since it the best possible solution for accepting every input...)
int main() {
char c;
while ((c = getchar()) != '\n') /* Always remember to put parenthesis around
an assignment in a condition... */
putchar(c);
}
Add a newline to your input:-
int main() {
char c;
// Use fputc to modify input...
fputc('\n', stdin);
while ((c = getchar()) != '\n') /* Always remember to put parenthesis around
an assignment in a condition... */
putchar(c);
}
But, beware! This method will stop at the first iteration of newline it gets, so if you have something outside of the '\n', well it won't be printed...

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.

stopping `scanf` when user enters "." DOT

I am messing around with the function below, I want to end input capture when user enters a DOT character. It seems that getche() is not doing what it is intentended to do:
void Encode(FILE *fp)
{
char chWord[100];
char *chP;
printf("Enter a word or a sentence, close it by a \".\"\r\n");
scanf("%s",chWord);
if (chWord != '.')
{
for (chP = chWord; *chP != '\0'; chP++) //to print each digit till end of string \0
{
printf("%d ",*chP+10);
fprintf(fp, "%d ",*chP+10);
}
}
}
UPDATE
It seems that I was not clear enough. What I am trying to do is when user enters a DOT it should act like pressing ENTER key so the program goes to next step. Some sort of simulating ENTER key.
if (chWord != '.')
should be
if (*chWord != '.')
you are comparing a char pointer to a char instead of a char to another char.
be aware that the way this code is written the input ".123" will skip the printing segment. not sure if this is desireable to you or not.
The scanf family of function accept a (negative)character set as a format specifier.
You can do scanf("%[abc]", chWord); to accept only strings composed of the letters abc.
And you can also specify which characters not to accept. So scanf ("%[^.]", chWord); will accept a string composed of anything but a dot.
Edit
I forgot to mention, that the dot will remain in the input stream buffer, so to read and ignore it during the scanf itself (rather than flush the buffer or do a getchar), just add it to the end of the format string. I.e.:
scanf ("%[^.].", chWord);
OK, backing out that whole Answer based on your update...
The answer is no, there is no way to do what you want to do with scanf, or anything in standard C for that matter. What you're trying to do is platform (and possibly compiler) specific.
If you want to treat the '.' as a enter key press you have to do the magic yourself. So, since you didn't mention if you were using any specific OS or compiler I'll give you the first example that comes to mind.
This works with Windows MS VS:
#include <Windows.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
char key = 0;
int counter = 0;
char chWord[100] = {0};
while(counter < 100) {
while(!_kbhit()) { //While no key has been hit
Sleep(1); //Sleep for 1 ms
}
key = _getch(); //Get the value of the key that was hit
if(key == '.') //if it was a .
break; //act as if it were an "enter" key and leave
else
chWord[counter] = key;
counter++;
}
chWord[99] = '\0';
printf("The string was %s\n", chWord);
return 0;
}

Help with basic reading user input in C

I am currently just learning C and for a project I need to read in integer inputs from the user. Currently I am using code that looks like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
printf("Please enter your first number");
while((a = getchar()) != '\n') {
}
printf("test");
return 0;
}
Im not sure how to get the number with getchar and then store it in a variable i can use.
Also I'm using = '\n' in the while statement because I don't really understand how EOF works (as in the K&R book) because whenever i use EOF i go into this loop i cant get out of.
Thanks for any advice anyone can offer.
You can use scanf.
Have a look at this example:
printf("Please enter your first number ");
int number=0;
scanf ("%d",&number);
The scanf answer above mine is correct, but if you haven't read about addresses or format strings, it may be difficult to grok.
You can convert your character to its integer equivalent by subtracting '0' from it:
char c = getchar();
int n = c - '0';

Resources