开发者

loop scanf until user types nothing (hits enter twice) using while loop

I've tried using NULL but it doesn't work. Any ideas?

while (index != NULL) { //what expression must be passed here开发者_JAVA技巧?
printf("Enter a number\n");
scanf ("%d", &index);
//do some work
}


The decimal value for NULL in ASCII is 0, so if you enter this in your program now it will end. This is not the same as a newline character (10 in decimal).

In any case, scanf() will continue until you enter a value, so you will need to use some sort of sentinel value for the loop condition eg. if you are using only positive numbers - use a negative; if you have an upper limit, an arbitrary value beyond this. Otherwise you will have to do it some other way eg. input a string and convert to an int if it's not your exit character/string.


If you think about it, I bet you have never seen a real world program that prompts you for input like this. Why? Because it's almost impossible to write them correctly, and even more impossible to use correctly. The way real world programs work is to either use a GUI or to read input from a file/stream without prompting. Given this fact, I've never understood why so many newbie programmers want to prompt the user for input.

Having said that, there may be no value that you can enter in your code to terminate the loop. Are all integer values valid input for your program? If so, you need some other way of terminating, such as typing the end-of-file character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜