comparing data types after using scanf in C

PrisonLove

Hard Realist
Reaction score
78
Hey,

So the goal is to read input from the user using scanf(), which is easy enough, but I want to make certain that the user entered an integer, how would I do that? I'm making an integer linked list so the user needs to enter an int and I need to make sure that if he/she doesn't, they will be prompted again and again until they do.

This is a snippet of my code:

Code:
int userVal;
:
:
printf("Please enter an integer value: ");
scanf("%d", &userVal);
printf("\n");
curLoc = node_addAfter(curLoc, userVal);

Any thoughts?

Thanks!
 

PrisonLove

Hard Realist
Reaction score
78
Okay then one more question, how would I iterate through each character in an integer to check if it is a digit?
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
Basicly, bit shifting.
1 int = 4 byte -> 4 char
Code:
int myValue = 5;
char bytes[4];

bytes[0] = myValue >> 24;
bytes[1] = myValue >> 16;
bytes[2] = myValue >> 8;
bytes[3] = (char) myValue;

// bytes is not equal to the 4 chars of the int.
Might want to use & (AND) 0xFF for unsigned variables.
 

The Helper

Necromancy Power over 9000
Staff member
Reaction score
1,697
If you want you could make your input a string and use string functions on it

You can find the length of the string using Len (or length or whatever) and loop through each character
if each character is a digit convert the string to an integer at the end then use it to set the cursor location
 

Sgqvur

FullOfUltimateTruthsAndEt ernalPrinciples, i.e shi
Reaction score
62
JASS:
include <stdio.h> // fgets
include <stdlib.h> // for atoi?

char input[INPUT_SIZE]
int inputi

do

    inputi = atoi(fgets(input, input.size, stdin))
    mylist.addAfter(somenode, inputi)

while inputi != MY_STOP_CONST

// Okay then one more question, how would I iterate through each character in an integer(why integer?) to check if it is a digit? 
for int i = 0, i < input.size, i++
    char ch = input<i>

    if &#039;0&#039; &lt;= ch &lt;= &#039;9&#039;
        // ch is digit
</i>
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top