How can you get characters without the \n? - c

In my code below I am trying to ignore new lines. Is there a better way of doing this?
do
{
scanf("%c",&wouldCount);
} while(wouldCount == '\n');
original code
#include <stdio.h>
int main()
{
char Yes = 'Y';
char wouldCount;
int counter;
int start;
int end;
int increment;
const END_DEFAULT = 1;
const INCREMENT_DEFAULT = 1;
printf("Would you like to count?");
scanf("%c",&wouldCount);
while(wouldCount == 'Y' || wouldCount == 'y')
{
printf("Please enter start number.");
scanf("%d",&start);
printf("Please enter a number you would like to stop at?");
scanf("%d",&end);
printf("Please enter a number to increment by.");
scanf("%d",&increment);
if(end < start)
{
end = start + END_DEFAULT;
}
if(increment <= 0)
{
increment = INCREMENT_DEFAULT;
}
for(counter = start; counter < end; counter += increment)
{
printf("%d\n",counter);
}
printf("Would you like to count?");
do
{
scanf("%c",&wouldCount);
} while(wouldCount == '\n');
}
return 0;
}

you could change scanf("%c",&wouldCount); to scanf("\n%c",&wouldCount); as well as forgo the do/while loop. This will tell scanf to ignore an enter with no character entered.
see scanf c++ reference

Related

if/else statements in for loop not working

I'm trying to make a program that asks for user input and the for loop should check if the input of both user id and pin matches any of the ten pre-made account's user id and pin, like an authorization system
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
struct account{
int uid;
int pin;
int user_bal;
};
int main()
{
int scan_uid, scan_pin;
int att = 3;
bool loop = true;
struct account user[10];
user[0].uid = 1234;
user[0].pin = 123456;
user[1].uid = 4181;
user[1].pin = 308592;
user[2].uid =1111;
user[2].pin =111111;
user[3].uid =2222;
user[3].pin =222222;
user[4].uid =4444;
user[4].pin =444444;
user[5].uid =5555;
user[5].pin =555555;
user[6].uid =6666;
user[6].pin =666666;
user[7].uid =7777;
user[7].pin =777777;
user[8].uid =8888;
user[8].pin =888888;
user[9].uid =9999;
user[9].pin =999999;
for (int i; i <= 9; i++){
user[i].user_bal = 1000;
}
do{
printf("\nEnter your user ID: ");
scanf("%d", &scan_uid);
printf("Enter your pin: ");
scanf("%d", &scan_pin);
printf("\n--------------------------------------------\n");
att--;
for (int i; i <= 9; ++i){
//printf("\n%d", i);
//printf("\n%d", user[i].uid);
//printf("\n%d", user[i].pin);
//printf("\n%d", scan_uid);
//printf("\n%d", scan_pin);
if (user[i].uid == scan_uid && user[i].pin == scan_pin){
loop = false;
}
else{
printf("\nThe username or password is incorrect!");
printf("\nYou have %d attempt(s) left.", att);
if (att > 0)
{
printf("\nPlease try again.\n");
}
else if (att == 0)
{
printf("\nUnauthorized Access.");
printf("\nReport for stolen credit card uploaded.");
}
}
}
}while (att > 0 || loop == false);
return 0;
}
I tried the relatively same code in python and it works perfectly there. I also checked if the "i" is correct and incremented and if it scanned the user input correctly. all ok. But i've hit a brick wall trying to solve why it just skips the 'if/else' and just scans input again.
I also tried an 'else if ' that does the opposite(!=) of the initial 'if' statement, with no luck.
Thanks.
Others have already pointed out that you need to initialize int i with int i = 0 in your for loop.
However, I would additionally like to point out several other mistakes here. First, your loop condition appears to be incorrect:
while (att > 0 || loop == false)
You want to continue the loop in the case where they haven't entered the correct value yet and where they still have more attempts left. However, as written, this will continue to loop even if the user enters the correct password. I think that this should actually be
while (att > 0 && loop == true)
Also, most languages don't require you to explicitly compare to true and false, so the following is stylistically better:
while (att > 0 && loop)
Also, as written, it prompts the user to try again; however, it doesn't prompt the user for input again after the first time, so it's impossible for the user to try again. You need to prompt the user for input again inside the loop if their input was incorrect.
A few issues ...
As Dan said, initialize i to 0. This will fix the segfault.
When you do loop = false; you need break; immediately afterwards.
And, your do/while condition is wrong. Change while (att > 0 || loop == false); into while ((att > 0) && loop);
The placement of the "incorrect passwords" related printf is incorrect. It should come after the for.
Otherwise, the same error message will be repeated 9 times for a single incorrect answer.
And, we want to exit the do/while loop [immediately after the for loop] if we see loop become false.
Here is the refactored code. It is annotated:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
struct account {
int uid;
int pin;
int user_bal;
};
int
main(void)
{
int scan_uid,
scan_pin;
int att = 3;
bool loop = true;
struct account user[10];
user[0].uid = 1234;
user[0].pin = 123456;
user[1].uid = 4181;
user[1].pin = 308592;
user[2].uid = 1111;
user[2].pin = 111111;
user[3].uid = 2222;
user[3].pin = 222222;
user[4].uid = 4444;
user[4].pin = 444444;
user[5].uid = 5555;
user[5].pin = 555555;
user[6].uid = 6666;
user[6].pin = 666666;
user[7].uid = 7777;
user[7].pin = 777777;
user[8].uid = 8888;
user[8].pin = 888888;
user[9].uid = 9999;
user[9].pin = 999999;
for (int i; i <= 9; i++) {
user[i].user_bal = 1000;
}
do {
printf("\nEnter your user ID: ");
scanf("%d", &scan_uid);
printf("Enter your pin: ");
scanf("%d", &scan_pin);
printf("\n--------------------------------------------\n");
att--;
// NOTE/BUG: i is uninitialized
#if 0
for (int i; i <= 9; ++i) {
#else
for (int i = 0; i <= 9; ++i) {
#endif
// printf("\n%d", i);
// printf("\n%d", user[i].uid);
// printf("\n%d", user[i].pin);
// printf("\n%d", scan_uid);
// printf("\n%d", scan_pin);
if (user[i].uid == scan_uid && user[i].pin == scan_pin) {
loop = false;
// NOTE/FIX: no need to continue loop if we get a match
#if 1
break;
#endif
}
}
#if 1
// stop if everything matched
if (! loop)
break;
#endif
printf("\nThe username or password is incorrect!");
printf("\nYou have %d attempt(s) left.", att);
if (att > 0) {
printf("\nPlease try again.\n");
}
else if (att == 0) {
printf("\nUnauthorized Access.");
printf("\nReport for stolen credit card uploaded.");
}
} while (att > 0);
return 0;
}
In the above code, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k
First of all, you should initialize i to 0
To browse all array contents, you should increment i after the instruction NOT before (i++) instead of (++i)
Condition while loop is WRONG
Look at this version of your code, It works properly:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
struct account{
int uid;
int pin;
int user_bal;
};
int main()
{
int scan_uid, scan_pin;
int att = 3;
bool loop = true;
struct account user[10] = {0};
user[0].uid = 1234;
user[0].pin = 123456;
user[1].uid = 4181;
user[1].pin = 308592;
user[2].uid =1111;
user[2].pin =111111;
user[3].uid =2222;
user[3].pin =222222;
user[4].uid =4444;
user[4].pin =444444;
user[5].uid =5555;
user[5].pin =555555;
user[6].uid =6666;
user[6].pin =666666;
user[7].uid =7777;
user[7].pin =777777;
user[8].uid =8888;
user[8].pin =888888;
user[9].uid =9999;
user[9].pin =999999;
for (int i = 0; i <= 9; i++){
user[i].user_bal = 1000;
}
do{
printf("\n--------------------------------------------\n");
printf("\nEnter your user ID: ");
scanf("%d", &scan_uid);
printf("Enter your pin: ");
scanf("%d", &scan_pin);
printf("\n--------------------------------------------\n");
att--;
for (int i = 0; i <= 9; i++){
//printf("\n%d", i);
//printf("\n%d", user[i].uid);
//printf("\n%d", user[i].pin);
//printf("\n%d", scan_uid);
//printf("\n%d", scan_pin);
if (user[i].uid == scan_uid && user[i].pin == scan_pin)
{
loop = false;
break;
}
}
if (loop && att)
{
printf("\nThe username or password is incorrect!");
printf("\nYou have %d attempt(s) left.", att);
}
else if (! att && loop)
{
printf("\nUnauthorized Access.");
printf("\nReport for stolen credit card uploaded.\n");
}
else if (!loop)
{
printf("\nMatches !\n");
}
} while ((att > 0) && (loop == true));
return 0;
}

How can I monitor user input with getchar

I need to get a user input and check if it is a valid input.
The input must:
Start with space(may be multiple) or a number.
(Assuming condition one satisfied) After the number there may be any kind of characters as long as I manage to extract the number
Clarification for number valid values:
Can be multiple digit
Can't be negative number
Can't contain decimal point
Can't be scientific notation
Can't be hexadecimal
So I wrote this basic code which simply gets the input but I have no clue on where to start on applying these conditions
printf("Enter size of input:\n");
int c;
while((c=getchar())!='\n' && c!=EOF){
printf("%c",c);
}
For example :
Input - 4##2311413sadokalda ; expected output - 4
Input - !4a ; expected output - Invalid Size
You can have state machine as below.
printf("Enter size of input:\n");
int c;
int state = 0; //0 = space, 1 = number, 2 = number read
int number = 0;
while((c=getchar())!='\n' && c!=EOF){
switch(state)
{
case 0:
if (isdigit(c))
state = 1;
else if (c == ' ')
break;
else
//error
break;
case 1:
if (isdigit(c))
{
number = number*10 + (c-'0');
break;
}
else {
state = 2;
}
case 2:
printf ("%d\n",number);
}
}
You probably want something like this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char* argv[]) {
printf("Enter size of input:\n");
char input[100];
fgets(input, sizeof input, stdin);
if (!isdigit(input[0]))
{
printf("Invalid Size\n");
}
else
{
int inputsize = strtol(input, NULL, 10);
printf("%d\n", inputsize);
}
}
Based on the problem statement you have given, i think this should give you your desired output
EDITED (After a few clarifications):
int main()
{
int c;
int i=0;
while((c=getchar())!='\n' && c!=EOF)
{
if(isdigit(c) || (char)c==' ') //isdigit() function check if given variable is a digit
{ printf("%c",c);
i+=1;
}
else
{
break;
}
}
if(i==0)
{ printf("Invalid size"); }
}

C Program Looping Incorrectly

I'm just a beginner and I'm trying to use whatever I know to make a simple program that:
Asks the user to input the letter 'S' or 's'. The program loops if 's' is not input. If the user does input 's', the program then
Asks the user to input a number, 1 or 2. The program loops if the incorrect number is input.
The problem I'm having is that after 's' is successfully input and the user is asked to enter a number, if an incorrect number is input (not 1 or 2) the program asks the user to input a letter again from the beginning which is incorrect. The program loops from the very beginning and doesn't work anymore. Can anyone help me fix this please?
#include <stdio.h>
#include <ctype.h>
int function(int num);
int main()
{
char input,ch,temp,c[64],exit;
int i,invalid,num,index,flag,day;
invalid = 0;
num = 0;
size_t length = 0;
index = 0;
flag = 0;
do
{
puts("Enter the letter S to start the program:");
scanf("%c", &input);
while( input!='\n' && (ch=getchar())!='\n' && ch!= EOF);
{
if(isalpha(input)==0)
{
printf("Invalid input. Please input something.\n");
continue;
}
if(input == 'S' || input == 's')
{
printf("\nProgram start.");
while( sscanf(c, "%d", &num) != 1)
{
length = 0;
flag = 0;
num = 0;
printf("\nEnter 1 for Module A. Enter 2 for Module B. Enter here: ");
fgets(c, 63, stdin);
length = strlen(c);
for(index = 0; index < length; ++index)
{
if(c[index] < '0' || c[index] > '9')
{
flag = 1;
break;
}
}
if( flag)
{
printf("\nInvalid character\n");
continue;
}
if( sscanf(c, "%d", &num) != 1)
{
printf("\nNo input detected.");
continue;
}
if(num == 1)
{
printf("\nModule A Selected.\n");
return(0);
}
if(num == 2)
{
printf("\nModule B Selected.\n");
return(0);
}
}
}
else
{
printf("\nInvalid input.");
continue;
}
}
}
while(1);
}
Make the scanf into like this.
scanf(" %c",&input);
Then While getting the input from the user using fgets It will place the new line character into that buffer. So this will lead to fails this condition.
if(c[index] < '0' || c[index] > '9')
{
flag = 1;
break;
}
So make the this condition into like this.
length=strlen(c)-1;// to skip the new line character
Or else to like this.
length=strlen(c);
if ( c[length] == '\n' )
c[length]='\0';
Output After placing this,
Enter the letter S to start the program:
S
Program start.
Enter 1 for Module A. Enter 2 for Module B. Enter here: 1
Module A Selected.
Make this in you code.
if(num == 1)
{
printf("\nModule A Selected.\n");
return(0);
}
else if(num == 2)
{
printf("\nModule B Selected.\n");
return(0);
}
else
{
printf("\nInvalid option\n");
c[0]='\0'; // It is for satisfy the second while loop condition.
continue;
}
Note that the loop:
while( input!='\n' && (ch=getchar())!='\n' && ch!= EOF);
is limited to the one line by the semicolon at the end. The following code is not the body of the loop, despite indentation trying to pretend that it is.
Also note that getchar() returns an int, not a char; you cannot reliably assign the result to a char and then test it for EOF. Depending on the platform, you will either never detect EOF at all or you will misdetect EOF when some other character (often ÿ, y-umlaut, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS) is typed. You must use int ch;.
Here. I fixed the problem using the following code. This way the code does the following:
Scans letters 'S' or 's'. Keeps looping if these are not entered.
Scans either number 1 or 2. Keeps looping until either number is entered and then exits.
The program does not loop from the very beginning (by outputting "Enter 'S' to start program), if any number other than 1 or 2 in entered in part 2 of the program. This was the problem originally.
The following is the correct code:
#include <stdio.h>
#include <ctype.h>
int function();
char input,temp,c[64],ch,exit;
int i,invalid,num,index,flag,start;
start = 0;
invalid = 0;
num = 0;
size_t length = 0;
index = 0;
flag = 0;
int main()
{
do
{
puts("Enter the letter S to start the program: ");
scanf("%c", &input);
while( input!='\n' && (ch=getchar())!='\n' && ch!= EOF);
{
if(isalpha(input)==0)
{
printf("Invalid input. Please input something.\n");
continue;
}
if(input == 'S' || input == 's')
{
printf("\nProgram start.");
start = 1;
if(start == 1)
{
function();
return(0);
}
}
else
{
printf("\nInvalid input.");
continue;
}
}
}
while(1);
}
int function()
{
while( sscanf(c, "%d", &num) != 1)
{
length = 0;
flag = 0;
num = 0;
printf("\nEnter 1 for Module A. Enter 2 for Module B. Enter here: ");
fgets(c, 63, stdin);
length = strlen(c);
length --;
for(index = 0; index < length; ++index)
{
if(c[index] < '0' || c[index] > '9')
{
flag = 1;
break;
}
}
if( flag)
{
printf("\nInvalid character\n");
continue;
}
if( sscanf(c, "%d", &num) != 1)
{
printf("\nNo input detected.");
continue;
}
if(num == 1)
{
printf("\nModule A Selected.\n");
return(0);
}
else if(num == 2)
{
printf("\nModule B Selected.\n");
return(0);
}
else
{
printf("\nInvalid option\n");
c[0]='\0'; // It is for satisfy the second while loop condition.
continue;
}
}
}

Program written in C, loops indefinately or crashes after a while

this is both my first time asking a question and also one of my first times writting such a big programm. As you might guess im new at programming.
Alright the source code:
#include <stdio.h>
typedef struct{
int **a;
int size;
}_board;
typedef _board* board;
typedef struct{
int row,col;
}position;
int main () {
int i, j, turn=1, victory = 0, num=0;
_board b;
char P1symbol, P2symbol, mark, boardarray[b.size][b.size];
position p;
printf("WELCOME TO THE GAME OF TIC TAC TOE!\n");
do {
printf("\nwill player one, use X or O as his symbols? select by pressing x or o\n");
scanf(" %c", &P1symbol);
if (P1symbol == 'x' || P1symbol == 'o') {
num = 1;
}
} while ( num == 0);
if (P1symbol == 'x') {
P2symbol = "o";
}
else {
P2symbol = "x";
}
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
for (i=0; i=b.size; i++){
for (j=0; j=b.size; j++){
boardarray[i][j] = "-";
}
}
do {
do {
boardsketch(boardarray, b.size);
if (turn%2 == 1) {
printf("player 1, please choose a box to input you mark on");
mark = P1symbol;
}else{
printf("player 2, please choose a box to input you mark on");
mark = P2symbol;
}
printf("type the coordinates i,j, which correspond to the row and collumn number");
printf("make sure the numbers are valid, not taken, and between 0 and %d", b.size);
scanf("%d %d", &p.row, &p.col);
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != "-");
turn++;
boardarray[p.row][p.col] = mark;
} while (wincheck(boardarray, p.row, p.col, b.size) != 1);
return 0;
}
int wincheck(int row, int col, int size, char boardarray[size][size])
{
if (boardarray[row][col] = boardarray[row -1][col -1] = boardarray[row +1][col +1]) {
return 1;
}
if (boardarray[row][col] = boardarray[row -1][col] = boardarray[row +1][col]) {
return 1;
}
if (boardarray[row][col] = boardarray[row][col -1] = boardarray[row][col +1]){
return 1;
}
if (boardarray[row][col] = boardarray[row -1][col +1] = boardarray[row +1][col -1]){
return 1;
}
}
void boardsketch(int size, char boardarray[size][size]) {
int i, j;
for (i=0; i=size; i++) {
for (j=0; j=size; j++) {
if (boardarray[i][j] == '-') {
printf("| ");
} else {
printf("%c |", &boardarray[i][j]);
}
}
}
}
Now the program's purpose is to simulate a game of tic tac toe (with the addition of the user, deciding the size of the game board). My problem is that, altough compilation IS achieved the program does 2 wierd behaviors when reaching a specific line, that line being:
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
If i input a value that doesnt obey to b.size <= 0, the printf above, repeats indefinately, if i DO put a correct value, the programm doesnt resume. What am i doing wrong? again im new at programming sooooo... go easy on me :D
There are compiler errors in your code. I don't know how you got it to compile and build it the first place.
Compiler errors:
You have:
P2symbol = "o";
Type of "o" is char const*. The type of P2symbol is char. What you need is
P2symbol = `o`;
Few lines after that, you have:
P2symbol = "x";
That needs to be changed to:
P2symbol = `x`;
Few lines after that, you have:
boardarray[i][j] = "-";
It suffers from the same compiler error. You need to change it to:
boardarray[i][j] = `-`;
Your declaration and definition of boardsketch does not match with the way you are calling it. Your call is:
boardsketch(boardarray, b.size);
You have defined it as:
void boardsketch(int size, char boardarray[size][size]) {
....
}
You need to change either the call or the function definition so that they match. Also, you should declare the function before it is used. Add
void boardsketch(int size, char boardarray[size][size]);
before the start of main.
The definition and call of wincheck suffers from the same error. It also should have a declaration before it's usage.
A few lines after that call to boardarray, you have the line:
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != "-");
The last part of that statement suffers from the char and char const* mismatch. You need to change it to:
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != '-');
Run Time Errors:
You have:
_board b;
char P1symbol, P2symbol, mark, boardarray[b.size][b.size];
The problem with that is b.size is not initialized. It could be anything. Using it to declare broadarray is problem. Imagine the chaos that will ensue if the b.size were to be initialized to a negative number. For sane and predictable behavior, you should initialize b properly before using its data.
A few lines below, you are asking for size to be input by the user.
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
There is a logic error here. You are asking for the size of the board after you have already created boardarray. What you could do is gather the initial input and use them to call another function where the core of the game play happens.
/* Function that contains the core part of playing the game */
void playgame(char P1symbol, char P2symbol, int size)
{
int i, j, turn=1, victory = 0;
char mark, boardarray[size][size];
position p;
for (i=0; i=size; i++){
for (j=0; j=size; j++){
boardarray[i][j] = '-';
}
}
do {
do {
boardsketch(size, boardarray);
if (turn%2 == 1) {
printf("player 1, please choose a box to input you mark on");
mark = P1symbol;
}else{
printf("player 2, please choose a box to input you mark on");
mark = P2symbol;
}
printf("type the coordinates i,j, which correspond to the row and collumn number");
printf("make sure the numbers are valid, not taken, and between 0 and %d", size);
scanf("%d %d", &p.row, &p.col);
}while (p.row > size && p.row < 0 && p.col > size && p.col <0 && boardarray[p.row][p.row] != '-');
turn++;
boardarray[p.row][p.col] = mark;
} while (wincheck(p.row, p.col, size, boardarray) != 1);
}
Now, main can be simplified to:
int main () {
char P1symbol;
char P2symbol;
int size;
int num = 0;
printf("WELCOME TO THE GAME OF TIC TAC TOE!\n");
do {
printf("\nwill player one, use X or O as his symbols? select by pressing x or o\n");
scanf(" %c", &P1symbol);
if (P1symbol == 'x' || P1symbol == 'o') {
num = 1;
}
} while ( num == 0);
if (P1symbol == 'x') {
P2symbol = 'o';
}
else {
P2symbol = 'x';
}
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &size);
}while (size <= 0);
playgame(P1symbol, P2symbol, size);
return 0;
}
Ah, the problem is your for loop after the do while. You are assigning your counters instead of evaluating the limits. Asigning them will result to true every time. Try this instead:
for (i=0; i<b.size; i++){
for (j=0; j<b.size; j++){
boardarray[i][j] = "-";
}
}
Also, do not create an array with undefine value b.size...

Logic in detecting int in C

I would appreciate some help with this. I'm trying to create this simple program that repeatedly loops asking for the user to enter in an int. If he enters an int, it exits but if he enters something else or bigger than int (ex.4gs4r33) it will loop again asking to enter an int. This is what I have tried, and it's not working. It says it's an int even if it's not.
#include<stdio.h>
unsigned int findInt();
int main() {
printf("Please input an int.\n");
findInt();
}
unsigned int findInt() {
char input;
long num = 0;
int b = 0;
do {
scanf("%c", &input);
if (isdigit(input)){
num = num*10+input+'0';
b = 1;
}
else if (input == '\n')
b = 1;
else
b = 0;
} while(input != '\n');
if (b == 1)
printf("Great!\n");
else{
printf("Not an int \n");
findInt();
}
return 0;
}
Two possible approaches. One would be to modify your code:
b = 1; // start off with good intentions…
do {
scanf("%c", &input);
if (isdigit(input)){
num = num*10+input -'0'; // *** SUBTRACT '0', don't add it!
}
else if (input != '\n') {
b = 0;
break; // *** break when you find non-digit
}
} while (input != '\n');
Two changes: getting the math right as you compute the integer, and fixing the logic (so you break out of your loop when you find a non digit character)
Second approach:
char buf[100];
char intAsString[100];
fgets(buf, 100, stdin);
sscanf(buf, "%d", num);
sprintf(intAsString, "%d\n", num);;
if(strcmp(buf, intAsString) == 0 ) {
printf("yay - you entered an integer!\n");
}
I'm sure you can figure out how that works.
update a complete code snippet that solves the issue of "loop logic" as well: you call the findInt function once from the top level, and it keeps going until you get the int. Note - in order for this to work properly, I read the entire input at once (rather than one at a time), then pick off the characters one by one using sscanf (and updating the pointer manually). It has a number of advantages - not least of which is that you start with a fresh input every time you call findInt, instead of having the rest of the input buffer that still needs reading (and which was giving rise to "no,no,no,great!" - as you would keep reading the bad input until you got to the newline, and accept that...)
#include<stdio.h>
#include <ctype.h>
unsigned int findInt();
int main() {
findInt();
}
unsigned int findInt() {
char input;
char buf[100];
char *temp;
long num = 0;
int b = 0;
printf("please enter an int:\n");
fgets(buf, 100, stdin);
temp = buf;
do {
sscanf(temp++, "%c", &input);
if (isdigit(input)){
num = num*10+input-'0';
b = 1;
}
else if (input == '\n')
{
b = 1;
break;
}
else {
b = 0;
break;
}
} while(input != '\n');
if (b == 1)
printf("Great! %d is an integer!\n", num);
else{
printf("Not an int \n");
findInt();
}
return 0;
}
In the else branch - i.e. not a digit or a newline - you set b to 0. Now if a digit DOES follow you reset that to 1.
You'll probably want to break or somehow record the permanent failure instead of just continuing.
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
void findInt(){
int x;
bool ok;
do{
char buff[32], *endp;
long long num;
ok = true;//start true(OK)
printf("Enter a number: ");
fgets(buff, sizeof(buff), stdin);
//strtoll : C99
x=(int)(num=strtoll(buff, &endp, 0));//0: number literal of C. 10 : decimal number.
if(*endp != '\n'){
if(*endp == '\0'){
printf("Too large!\n");//buffer over
while('\n'!=getchar());
} else {
printf("Character that can't be interpreted as a number has been entered.\n");
printf("%s", buff);
printf("%*s^\n", (int)(endp - buff), "");
}
ok = false;
} else if(num > INT_MAX){
printf("Too large!\n");
ok = false;
} else if(num < INT_MIN){
printf("Too small!\n");
ok = false;
}
}while(!ok);
}
,

Resources