Read user input until a specific character is encountered - c

Can someone please provide me some examples? Thank you :)
#include <stdio.h>
int main()
{
int tcount = 0, ccount = 0, dcount = 0;
char ch;
printf("Enter your characters (! to end): \n");
/* What program code to write to get the result? */
printf("digits: %d\n", dcount);
printf("letters: %d\n", ccount);
return 0;
}
is it using for loop?
for (tcount=0;tcount<10;tcount++)
{
scanf("%c",&ch);
if(ch == '!')
break;
}
Test Result:
hello 5432 user#
digits: 4 letters: 9

I would recommend you to use getchar() instead of scanf() for reading single characters.
Or if you have to, you have to skip leading whitespaces
scanf(" %c",&ch);
^ Note the space
Here is a simple example which could be helpful to you, using functions isdigit() and isalpha() from ctype.h library.
int c, numberCounter = 0, letterCounter = 0;
while ((c = getchar()) != '!')
{
if (isalpha(c))
{
letterCounter++;
}
else if (isdigit(c))
{
numberCounter++;
}
}
If you can't use additional libraries like ctype.h, take a look at the ASCII table, for example
if (c >= '0' && c <= '9') // '0' == 48, '9' == 57
{
// c is digit
}

Try something like:
do
{
char c = getchar();
if(c!='!')
{
... do something ....
}
}
while(c != '!');

Yes you need to use a loop for, or a while:
for (tcount=0;tcount<10;tcount++)
{
scanf("%c",&ch);
if(ch == '!')
break;
}
or the while code:
while(ch != '!'){
scanf("%c",&ch);
printf("There are nothing to see here");
}

The POSIX getdelim function does exactly what you're asking for (most code floating around uses getline, but it is exactly the same other than the extra argument). Beware the possibility that the delimiter does not occur within the buffer size.
Also, for interactive input, you might want to put the TTY in raw mode, or the user will have to press enter anyway.

Related

read ints from standard input until \n is found

I'm trying to make a function that reads ints from stdin. it has to read until a certain amount of numbers is read (count in example below), or until it finds a '\n'.
Since as far as I am aware scanf (with %d format specifier) ignores newlines, I used getchar and converted the character into the number it should be.
this works but only for 1 digit numbers.
is there any better way to achieve this?
This is my code:
char num = getchar();
while (num != '\n' && count < 9) {
//boring operations that don't matter
num = getchar()
}
Reading via fgets() is better. Continue reading if your must use scanf().
To use scanf("%d",...), we need extra care to read a line. As "%d" consumes leading white-space, including '\n', we need more code to look for white-space and test if a '\n' is found.
int count = 0;
while (count < 9) {
// Read leading spaces
int ch;
while (isspace((c = getchar())) && c != '\n') {
;
}
if (c == '\n' || c == EOF) break; // We are done reading
ungetc(c, stdin); // put character back
int some_int;
if (scanf("%d", &some_int) == 1) {
printf("Integer found %d\n", some_int);
count++;
} else {
// Non-numeric input, consume at least 1 character.
getchar();
}
}
If numeric text is outside the range of int, the above use of "%d" is undefined behavior. For robust code, use fgets().
The %d conversion specifier only ignores leading whitespace. So you can do something like:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int n = argc > 1 ? strtol(argv[1], NULL, 10) : 10;
int x;
while( n-- && scanf("%d%*[ \t]", &x) == 1 ){
printf("Read: %d\n", x);
int c = getchar();
if( c == EOF || c == '\n' ){
break;
}
ungetc(c, stdin);
}
return 0;
}
However, this will probably not handle a stream like 10 5 x in a reasonable way. You'll need more logic on the first non-whitespace after an integer to handle that (maybe just do if( c == EOF || ! isdigit(c) ){ break; }). Parsing data with scanf if fickle (it really never has a purpose outside of university exercises). Just use fgets and strtol.
scanf() doesn't ignore \n
#include <stdio.h>
#include <stddef.h>
int main(int argc , char *argv[])
{
int b;
char c;
scanf("%d%c",&b,&c);
if(c == '\n') printf("and then " );
}
Someone posted an answer and then deleted but it was the perfect solution for my problem, so all credit to the original author.
The solution was reading normally with scanf and afterwards,with getchar, checking if it was \n or EOF. If it was break out of the cycle, if it wasn't, "unread" with ungetc so you can scanf the number in the next iteration.
So my final code looks like this:
while(scanf("%d",&num) == 1 && count<9){
//boring operations
c = getchar();
if (c == EOF || c == '\n') break;
if (ungetc(c,stdin) == EOF) break;
}
NOTE: like Andrew Henle pointed out in the replies, this doesn't work unless it is guaranteed that there isn't any space between the digits and the newline

Write a program to check given input string have balance brackets

Given a string of parentheses, write a program to find whether its valid or not.
Examples-
input : {{{}}}
output: Valid
input : }{}{}{}}
output: Invalid
I wrote the following code in C and tested that the output were coming correct.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[20];
int i=0;
printf("Enter String: ");
gets(str);
int count = 0;
while (str[i] != '\0')
{
if (str[i] == '}')
count--;
if (str[i] == '{')
count++;
if (count < 0)
{
printf("\nInvalid");
break;
}
i++;
}
if (count == 0)
printf("\nValid");
return 0;
}
This program doesn't work for the case where input is {{{}}, what condition(s) am I missing?
Code should state if the final result is not 0 as in the case of "{"
if (count == 0) {
printf("Valid\n");
} else {
printf("Invalid\n");
}
return 0;
Also simple break out of loop.
if (count < 0) {
// printf("\nInvalid");
break;
}
gets() has been depreciated since C99 and eliminated from C (C11), use fgets().
char str[20];
fgets(str, sizeof str, stdin);
There is no need to read the entire string in. Code could use 1 char ar a time.
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
if (str[i] == '}')
count--;
if (count < 0) {
break;
}
else if (str[i] == '{')
count++;
}
}
You don't really need to input the whole string at once since you're only every sequentially processing the characters. Hence you can avoid using unsafe methods like gets() and even safe-but-complicating methods like fgets().
Instead, just use getchar() to read and process each individual character - that should greatly simplify what you need to do.
As to the logic, you basically have it right. Maintain the bracket level, a value initially set to zero. Then read each character and action it as follows:
If it's {, just add one to the level.
If it's }, subtract one from the level, then check to ensure the level is non-negative. If not, then you've had too many closing brackets and you can exit.
If it's end of line or end of file, stop processing characters. Check to make sure the final level is zero. If not, you haven't closed off all the brackets so it's invalid. If the level is zero, everything is balanced.
Any other character can be considered an error.
See below for one example on how to implement this:
#include <stdio.h>
int main (void) {
int debug = 0; // for debugging purposes.
int ch, level = 0; // character and current level.
// Output prompt, read characters while valid.
printf("Enter string: ");
while (((ch = getchar()) == '{') && (ch == '}')) {
// Select based on '{' or '}'.
if (ch == '{') {
// Open bracket, just add one.
++level;
if (debug) printf("DEBUG: {:%d\n",level);
} else {
// Close bracket, subtract one and check.
if (--level < 0) {
puts ("Level has gone below zero.");
return 1;
}
if (debug) printf("DEbug: }:%d ",level);
}
}
// If not endline/endfile, we have invalid character.
if ((ch != '\n') && (ch != EOF)) {
puts ("Invalid character in input.");
return 1;
}
// Level should be zero.
if (level != 0) {
puts ("Level still positive at end of line.");
return 1;
}
// All checks now passed okay.
puts ("Input was fine.");
return 0;
}
You should never use gets(), the gcc compiler even warns about it being dangerous because there is no way to prevent a buffer overflow, for example
char str[6];
gets(str);
with the following input
iharob
is a problem, because there is no room for the '\0' terminator or the '\n', instead
fgets(str, sizeof(str), stdin);
would be safe with any input, although the input string would be trimmed to fit the buffer, but no buffer overflow will occur.
Previous answers have covered avoiding buffer overflows and potential cases where it will not work - to improve performance I would modify the while loop to avoid checking conditions which we know will always be false. e.g. no point in checking if count is less than 0 unless we just decreased the count; no point in checking for an open bracket if the character was a close bracket:
while (str[i] != '\0')
{
if (str[i] == '}')
{
count--;
if (count < 0)
{
printf("\nInvalid");
break;
}
}
else if (str[i] == '{')
count++;
i++;
}
I hope you find this useful and simple ^-^
#include<iostream>
#include<string.h>
using namespace std;
{
string mathEx ;
cout<<"Please Enter math Expression contain ')' , '(' to
check balance \n"<<"MathExpression = ";
cin>>mathEx ;
int i =0 , count = 0 ;
while (mathEx [i] != '\0'){
if(mathEx[i]=='('){
count++;
}
if(mathEx[i]==')'){
count--;
}
if(count<0){
break ;
}
i++;
}
if(count==0){
cout<<"True !";
}
else {
cout<<"Invalid !"<<endl;
}
return 0;
}

C programming getchar()

I have two problems writing my code. The first problem I have is getting my getchar() to work if the user enters no text and just hits enter. I need to print an error if they do so and prompt the user to reenter the text in a loop until they do enter text. Is there any way to do so because everything I have tried has failed.
Here is the code I have for that section:
printf("Enter a text message: ");
while((c=getchar()) != '\n' && c != EOF)
{
text[i]= c;
i++;
}
I am new to C so I am limited on ideas to fix my dilemma. As you can see I am setting the input equal to an array. This leads to my second problem, I need to limit the input to no more than 100 characters. But, instead of giving the user an error I need to just chop off the extra characters and just read the first 100.
The simplest solution to your problem is to use fgets. We can give limit to the input so that it doesn't read the extra characters after the given limit.
Refer this sample code. Here I am printing the string if the user is not pressing Enter key:
#include <stdio.h>
int main()
{
char str[100];
fgets(str, 100, stdin);
if(str[0] != '\n')
{
puts(str);
}
return 0;
}
#include <stdio.h>
#define MAXSIZE 100
int main() {
char text[MAXSIZE+1]; // one extra for terminating null character
int i = 0;
int c;
while (1) {
printf("Enter a text message: ");
i = 0;
while ((c = getchar()) != '\n' && c != '\r' && c != EOF) {
if (i < MAXSIZE) {
text[i]= c;
i++;
}
}
if (i > 0 || c == EOF)
break;
printf("Empty string not allowed.\n");
}
text[i] = '\0';
printf("You entered: %s\n", text);
return 0;
}
Test code to detect non-compliant system:
#include <stdio.h>
int main() {
int c;
printf("Just hit enter: ");
c = getchar();
if (c == '\r')
printf("\\r detected!!!\n");
else if (c == '\n')
printf("\\n detected.\n");
else
printf("Yikes!!!\n");
return 0;
}
First of all getchar() can take only one character an input. It cannot take more than one character.
char c;
int total_characters_entered = 0;
do
{
printf ("Enter a text message: ");
c = getchar();
if (c != '\n')
{
total_characters_entered++;
}
} while (total_characters_entered <= 100);
I have written some code that will iterate in while loop until user has entered 100 characters excluding "Simple Enter without any text"
Please let me know if it does not satisfy your requirement. We will work on that.

Basic C programming

I'm trying to write a program which given a certain number of input will output the product of the listed input (only accounting inputs of 0-9 and ignoring other).
For example:
input:345 would result output: 60, or another example would be, input: 3t4 and output: 12
I have given it many attempts and this is what I'm stuck with :
#include <stdio.h>
main(){
int c,i;
c = getchar();
i = 1;
while (c!= '\n'){
if (c>=48 && c<=57){
i=c*i;
c=getchar();
}
}
printf("%d",i);
}
How can i do this ?
Couple of issues in your code.
After each time the program encounters a non-numeric character it doesn't read further from the input. It reads the same character. Hence c=getchar() should be outside the if block
The multiplication happens for the char variable c. It should be converted to the actual number and then be multiplied. In your code you are multiplying its ascii value. Hence (c-48)*i instead of c*i
Use i=(c-48)*i; instead of i = c*i. So, the changed program would be:
#include <stdio.h>
main(){
int c,i;
c = getchar();
i = 1;
while (c!= '$'){
// printf("%c\n", c);
if (c>=48 && c<=57){
i=(c-48)*i;
}
c=getchar();
}
printf("%d",i);
}
This will ensure that you are using the numeric value of the digit, 0 not as ascii code of 0 but as simple 0.
use c=getchar() outside the if block. This should work.
int i,c;
i = 1;
while (i){
c=getchar();
if(c == '\n')
{
break;
}
if (c < 48 || c > 57)
{
i = -1;
break;
}
i = i * (c-48);
}
if (i == -1)
{
printf("Error. Non-Number Entered\n\n");
}
else {
printf("%d\n\n",i);
}

Counting input characters in C

I have just started learning C, been reading a C textbook by Keringhan and Ritchie. There was this example in the textbook, counting characters from user input. Here's the code:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF) {
if (getchar() != 'q')
++nc;
else
break;
}
printf("%ld\n", nc);
}
The problem is, when I execute the code, if I input only one character per line, when I input "q" to break, it doesn't do so. I have to type some word per line, only after that it will break the loop. Also, it only counts the half of the characters of the word. I.e. if I input
a
b
russia
it will only print '5' as final result.
Could you please explain to me why is this happening?
This works, but only when you finish off with an Enter. So, this will count the characters until the first "q" appears. That is just how getchar() and getc(stdin) work.
#include <stdio.h>
int main() {
char c = 0;
long count = 0;
short int count_linebreak = 1; // or 0
while((c = getchar()) != EOF) {
if(c != 'q' && (count_linebreak || (!count_linebreak && c != '\n'))) {
++count;
}else if(c == 'q') {
printf("Quit\n");
break;
}
}
printf("Count: %ld\n",count);
return 0;
}
A StackOverflow question about reading stdin before enter
C read stdin buffer before it is submit

Resources