Click to See Complete Forum and Search --> : Logic Error (Simple IF Statement)


1991dan
October 5th, 2009, 11:58 PM
I have the following block of code...



int counter2 = 0;

while(counter2 < 1) {

printf("What time of the day were you travelling at? Was it at the peak
scanf("%d", &timeofday);

if(timeofday == 1 || timeofday ==2) {
counter2 = counter2 + 1;
}
else
printf("ERROR; incorrect input.");

}


I wanted to keep prompting the user for this question until the integer "1" is entered. I don't think the IF statement is ever true regardless if I were to enter a 1, or not. Simply because I am comparing the input from the user with an integer, which i believe is the problem. But.. how would i be able to fix this?

boudino
October 6th, 2009, 07:51 AM
1. parse the input to get an integer
2. compare string to string, something like
if(timeofday == "1" || timeofday == "2") {

1991dan
October 6th, 2009, 09:22 AM
1. parse the input to get an integer
2. compare string to string, something like
if(timeofday == "1" || timeofday == "2") {

When I tried to use the quotations and compare string to string, the compiler said that i was trying to compare between a pointer and an integer.

darwen
October 6th, 2009, 09:22 AM
2. compare string to string, something like


The code sample appears to be C++ - try the c++ forums not the C# forums.

Darwen.

1991dan
October 6th, 2009, 09:36 AM
The code sample appears to be C++ - try the c++ forums not the C# forums.

Darwen.

This is what I have tried to do in my attempt to parse the user input, still generate error.


int timeParse = 0;
do{

while(counter2 < 1) {
printf("What time of the day were you travelling at? Was it at the peak
scanf("%d", &timeofday);
int timeParse = int.Parse(timeofday);


printf("made it here");
counter2 = counter2 + 1;
if(timeParse == 1 || timeParse == 2){
counter2 = counter2 + 1;
}
else{
printf("ERROR; Please enter a valid input.");
}
}


ERROR: assignment1.c:16: error: expected expression before 'int'

darwen
October 6th, 2009, 10:34 AM
scanf and printf are both C/C++ methods. They don't exist in C#.

Are you trying to write a C# application or a C/C++ application ?

You are aware that they are completely different languages ?

Darwen.

boudino
October 7th, 2009, 02:20 AM
I think the intention is clear, rewrite it to the language you are using. I think that it could be something like

if(timeofday* == "1" || timeofday* == "2")