【发布时间】:2015-09-24 03:26:53
【问题描述】:
我尝试编写一个程序,使用 scanf() 函数从字符串读取未知数量的输入(仅数字)。但似乎对这种情况不太满意:我输入了 9,但程序只读取了其中的 5。
#include<cstdio>
#include<cstring>
using namespace std;
int top=0,heap[65535];
void add_up(int x){
int next=x>>1,now=x;
while(next){
if(heap[now]<heap[next]){
heap[now]^=heap[next]^=heap[now]^=heap[next];
now=next;
next=now>>1;
}
else{
break;
}
}
return ;
}
void add_down(){
int now=1,next=now<<1;
while(next<=top){
if(next<top&&heap[next]>heap[next+1])next++;
if(heap[now]<heap[next])break;
heap[now]^=heap[next]^=heap[now]^=heap[next];
now=next;
next=now<<1;
}
return ;
}
int main(){
memset(heap,0,sizeof(heap));
int i;
while(scanf("%d",&i)!=EOF){
// for(int j=0;j<10;j++){
scanf("%d",&i);
printf("%d ",i);
heap[++top]=i;
add_up(top);
}
printf("\n");
while(top>0){
printf("%d ",heap[1]);
heap[1]=heap[top--];
add_down();
}
printf("\n");
return 0;
}
发现这个真是太棒了:
E:\home\Desktop>echo 9 8 7 6 5 4 3 2 1 > try001.txt
E:\home\Desktop>gcc -g try001.cc -o try001
E:\home\Desktop>try001.exe < try001.txt
8 6 4 2 1
1 2 4 6 8
E:\home\Desktop>
输入文件中有9个数字,为什么程序只读取5个! 而如果我想读取未知数量的输入,我该怎么做?
【问题讨论】:
-
我只想使用 cstdio 头文件,拜托。
-
heap[now]^=heap[next]^=heap[now]^=heap[next];导致未定义的行为,这意味着您的程序可以做任何事情。尝试编写正确的代码,而不是试图通过使用 hacks 来变酷 -
@TJM:为什么?那你为什么要写 C++?这本质上是 C 代码。
-
@Lightness Races in Orbit 因为,如果我使用 C,编译器不会接受它。
标签: c++