LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 912|回复: 13

问一个很弱的问题啊~

[复制链接]
发表于 2003-9-20 12:38:01 | 显示全部楼层 |阅读模式
c里面怎么在控制台读数据,如果是数字就保存,如果是'q'就退出呢?
用scanf吗?还得转换一下?怎么用啊?
发表于 2003-9-20 17:45:03 | 显示全部楼层
分清是从控制台读还是从标准输入读
1. open("/dev/tty2")
   read(..)
2. read(0,...)直接从标准输入读.

明白标准输入输出,错误输出,和管道,在Unix 中是很重要的.
 楼主| 发表于 2003-9-20 22:10:59 | 显示全部楼层
不明白拉
小弟是初学啊
发表于 2003-9-20 23:03:38 | 显示全部楼层
使用sanf也可以啊
或是fread(stdin,...
或是其它的
如getc
 楼主| 发表于 2003-9-20 23:35:02 | 显示全部楼层
能具体说说嘛?
发表于 2003-9-21 01:34:03 | 显示全部楼层
看看man 或是使用google查找这两个函数
发表于 2003-9-21 13:43:09 | 显示全部楼层

my prog

char c; //定义一个字符变量
int i, group[20];
while ((c=getchar()) != 'q'){ //循环的条件是没有按下"q"键
if (c>='0' && c<='9') //判断是不是数字,如果是执行下面代码
     for (i=0; i<=20; ++i)  //由于是数组,这里可存的数字最多19个
        group=c;
}

大概思想就是这样了,如果你还是写不出来,就叫让我写完整的代码吧(我现在没有时间,也觉得没有必要),在实现的时候你可以用链表,这样你输入多少个数字都可以容纳了(只要内存够)

:)
发表于 2003-9-21 13:46:17 | 显示全部楼层

补充一下

group[20]能够存的整型数字个数是20个,不过最后一个就不定的(它总是存最后输入的那个数字),所以我上面说可存19个数字。
发表于 2003-9-21 17:46:17 | 显示全部楼层

  1. char c;
  2. int i, group[20];

  3. while ((c=getchar()) != 'q'){
  4.   if (c>='0' && c<='9')
  5.     for (i=0; i<=20; ++i)
  6.       group[i]=c;
  7. }
复制代码

这个程序有问题,把for放在while的里面,最后得到的group全是最后输入的一个字符。
 楼主| 发表于 2003-9-21 18:04:33 | 显示全部楼层
谢谢各位~~我自己已经写的差不多了~。这是一个排序的程序,结果是正确的,只是有些行为我不太明白
完整代码如下:
#include <stdlib.h>
#include <stdio.h>

int checkData (char char_to_check[]);
int comp (const void *arg1, const void *arg2);

int main (int argc, char *argv[]){
    char str[10];  //save the  orginal input data
    int num[100];
    int count = 0;
    int i;
    printf("please enter the data,and non_numeric data to quit~!\n");
    while (count < 100){
       printf("enter the data_%d:\n",count+1);
       scanf("%s\n",&str);
       if (checkData(str) == -1)
          break;
       num[count++] = atoi(str);
    }

     qsort(&num,count+1,sizeof(int),comp);

     printf("the result is:\n");
     for (i = 0; i<count; i++)
        printf("%d ",num);
     printf("\n");

     exit(0);
}

int checkData(char char_to_check[]){
    int i;
    for (i = 0; i<strlen(char_to_check); i++)
      if (!(char_to_check>'0' && char_to_check<'9'))
         return -1;
    return 0;
}

int comp (const void *arg1, const void *arg2){
    return *(int *)arg1-*(int *)arg2;
}


运行结果如下:

please enter the data,and non_numeric data to quit~!
enter the data_1:
1
2
enter the data_2:
3
enter the data_3:
4
enter the data_4:
5
enter the data_5:
3
enter the data_6:
6
enter the data_7:
7
enter the data_8:
q
enter the data_9:
q
the result is:
1 2 3 3 4 5 6 7
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表