parse an int?

Sep 28, 2008 at 9:53pm
Im fairly new to C and C++, having been learning for four months now.

I'm curious to know if I can parse an int to check for a non-digit character entered. I know I could use a string of char's and use !isdigit() for each char, but I just want to know if there is a similar way for int's?

here are the important parts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <cstdlib>
#include <iostream>
#include <cctype>

typedef struct
{
    char name[20],email[50],phone[7];
    long id;
    
}students;

/*function protos*/   
void edit(students *vals);

int main(int argc, char *argv[])
{
  students stu[40];

  /*pointer to first array of struct*/
  students *sptr = stu;

  edit(sptr); //pass ptr to function
} 

void edit(students *vals)
{   
    int record=0;

while(1)
    {
        cout << "\n\t\t" << "Enter the student id [numbers only]:\t";
        cin  >> vals[record].id;
        
        if(vals[record].id  ) /* what to put here? */
            continue;
        else
            break;
    }
}
Sep 28, 2008 at 10:14pm
"Parsing an int" has no meaning. An int is information that is already understandable by a computer (as opposed to, say, "1024").
After the cin, you already have an integral value in vals[record].id. There's no processing to be done.
Sep 28, 2008 at 10:23pm
what if a char is entered.. program would crash b/c it is expecting an int?
Sep 28, 2008 at 10:27pm
Have you ever tried it? 'Cause I have, and that's not what happens.
1
2
3
4
5
6
7
8
#include <iostream>

int main(){
	int a;
	std::cin >>a;
	std::cout <<a<<std::endl;
	return 0;
}
Last edited on Sep 28, 2008 at 10:27pm
Topic archived. No new replies allowed.