如何输入不带空格的数字(int)?
只要输入不为零,我想停止scanf。 我该怎么办?
#include <stdio.h>
int main()
int num;
{
while(num!=0){
printf("Enter the account activity: ");
scanf("%d", &num);
if(num==0){
break;
}
}
}
答案 0 :(得分:1)
我冒昧地按摩了您的代码,并假设您想要一个总和...
#include <stdio.h>
int main(void) {
int num, sum = 0;
printf("Enter the account activity: ");
fflush(stdout);
for (;;) {
if (scanf("%d", &num) != 1) break;
if (num == 0) break;
sum += num;
}
printf("Result is %d.\n", sum);
return 0;
}
答案 1 :(得分:0)
例如,使用以下内容代替使用scanf
:
#include<stdio.h>
#define MAX 100
int main(void)
{
int i,count=0;
int num=0, block=0;
int sign=1;
int arr[MAX] = {[0 ... MAX-1]=-1};
while((i=getchar())!=EOF)
{
if(block==0) //FIRST THING TO BE ENTERED BY USER IS SIGN OF INTEGER
{
if(i=='-')
block=1;
sign=-1;
continue;
}
if((i>'0')&&(i<='9'))
{
arr[count++]= i -'0';
}
else
break;
}
i=0;
printf("The number is: ");
while(i<count)
{
num=arr[i++]+num*10;
}
printf("%d",sign*num);
return 0;
}
亲爱的投票者-请给我至少一个拒绝投票的理由
答案 2 :(得分:0)
/*Program that prints and stores(last integer value) and terminates on input value of 0 */
#include <stdio.h>
int main(){
int num=1;
while(num!=0){
printf("\nEnter the account activity: ");
scanf(" %d", &num);
if(num==0)
break;
}
return 0;
}
答案 3 :(得分:-1)
int main(void)
{
int num;
int ch = 0; // used for reading and discarding garbage from stdin
printf("Enter the account activity: ");
do {
if(scanf("%d", &num) == 1) // check if an in could be read successfull
printf("%d\n", num); // if so, print it.
else { // otherwise
// read characters from stdin until EOF is reached
while ((ch = getchar()) != EOF)
if (isdigit(ch) // if the last character
|| ch == '+' // was a valid character to
|| ch == '-') { // begin a new int,
ungetc(ch, stdin); // put it back into the stream
break; // and break the while
}
}
} while (num && ch != EOF);
}