读取没有数组的整数和/或字符

时间:2011-10-05 13:15:12

标签: c

我需要逐个读取整数,直到我读取'$',然后确定最大,最小等等。我可以使用一个字符变量并执行它,但它适用于0到9之间的数字。但是如何读取两个或多个数字的整数,同时检测'$' - 我使用了char *,但我猜它相当于一个数组,我不应该在这里使用它。此外,char包含单个数字/字符,因此不适合更大的数字。我该怎么办?

6 个答案:

答案 0 :(得分:2)

没有数组,没有指针,没有棘手的char-by-char读取&兑换。只需简单scanfgetchar

#include <stdio.h>

int main()
{
    int newValue=0;        /* value being acquired */
    int max;               /* current maximum value */
    int min;               /* current minimum value */
    int firstAcquired=0;   /* boolean flag set to 1 after first acquisition */
    int ch;                /* used as temporary storage for the getchar() */
    for(;;)
    {
        /* scanf returns the number of successfully acquired fields; here if it
           returns 0 means that the value couldn't be acquired */
        if(scanf("%d",&newValue)==0)
        {
            /* scanf failed, but it's guaranteed it put the offending character
               back into the stream, from where we can get it */
            ch=getchar();
            if(ch=='$' || ch==EOF)
                break;
            else
            /* from here to the break it's just to handle invalid input and EOF
               gracefully; if you are not interested you can replace this stuff
               with a random curse to the user */
            {
                puts("Invalid input, retry.");
                /* Empty the buffer */
                while((ch=getchar())!='\n' && ch!=EOF)
                    ;
            }
            /* if it's EOF we exit */
            if(ch==EOF)
                break;
        }
        else
        {
        /* Everything went better than expected */
            if(!firstAcquired || newValue>max)
                max=newValue;
            if(!firstAcquired || newValue<min)
                min=newValue;
            firstAcquired=1;
        }
    }
    if(firstAcquired)
    {
        printf("The maximum value was %d\n", max);
        printf("The minimum value was %d\n", min);
    }
    return 0;
}

答案 1 :(得分:1)

为了破坏所有的乐趣,炫耀,彻底的矫枉过正和愚蠢的乐趣:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
namespace qi = boost::spirit::qi;

template <typename V>
void show_statistics(const V& data)
{
    using namespace boost::spirit::karma;
    std::cout << "data:\t"<< format('{' << auto_ % ", " << '}', data) << std::endl;

    std::cout << "min:\t" << *std::min_element(data.begin(), data.end()) << std::endl;
    std::cout << "max:\t" << *std::max_element(data.begin(), data.end()) << std::endl;

    auto sum = std::accumulate(data.begin(), data.end(), 0);
    std::cout << "sum:\t" << sum << std::endl;
    std::cout << "avg:\t" << (1.0*sum) / data.size() << std::endl;
}

void dostats(const std::vector<int>& data) { show_statistics(data); }

int main()
{
    std::cin.unsetf(std::ios::skipws);
    auto f = boost::spirit::istream_iterator(std::cin);
    decltype(f) l;

    bool ok = qi::phrase_parse(f, l, +(+qi::int_ > "$") [ dostats ], qi::space);

    if (f!=l)
        std::cout << "Remaining input unparsed: " << std::string(f,l) << std::endl;

    return ok? 0:255;
}

演示:

示例运行:

sehe@natty:/tmp$ ./test2 <<< "1 2 3 4 5 $ 3 -9 0 0 0 $ 900 9000 $ unparsed trailing text"
data:   {1, 2, 3, 4, 5}
min:    1
max:    5
sum:    15
avg:    3
data:   {3, -9, 0, 0, 0}
min:    -9
max:    3
sum:    -6
avg:    -1.2
data:   {900, 9000}
min:    900
max:    9000
sum:    9900
avg:    4950
Remaining input unparsed: unparsed trailing text

答案 2 :(得分:0)

您可以使用'scanf(“%s”)'来读取一组字符。然后,您可以检查第一个字符是否为'%',如果是,则终止。否则,请调用atoi转换为整数。存储最大和最小的整数类型,而不是字符类型。

基本上,你必须处理角色的唯一时间是你读它们并检查它是否是'$'。否则,一直使用整数。

答案 3 :(得分:0)

你可以在循环中通过char读取char,检查值等等......

int i = 0;
char c = 0;
int size = 10;
int currentIndex = 0;
int* integers = malloc(sizeof(int) * size);
int counter = 0;
do
{
    scanf("%c", &c);
    if (c == ' ') // Match space, used a number separator
    {
        if (counter != 0 && i != 0)
        {
            if (currentIndex >= size)
            {
                size += 5;
                integers = realloc(integers, size);
            }
            integers[currentIndex] = i;
            currentIndex++;
        }
        counter = 0;
        i = 0;
    }
    else if (c >= '0' && c <= '9')
    {
        i = (i * counter * 10) + (c - '0');
        counter++;
    }
}
while(c != '$');

最后不要忘记free整数!

答案 4 :(得分:0)

如果我正确得到你想要的东西,它应该是这样的:

int i = 0;
char c = getchar();
while (c != '$')
{
    i = i * 10 + (c - '0');
    c = getchar();
}

希望它有所帮助。

答案 5 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define BUFF_SIZE 16
#define DATA_MAX_SIZE 64

int main(){
    char buff[BUFF_SIZE];
    int data[DATA_MAX_SIZE];
    int i,value,counter = 0;
    char *buffp,*p;
    while(NULL!=fgets(buff,BUFF_SIZE,stdin)){
        buff[BUFF_SIZE - 1]='\0';
        buffp = buff;
next:   while(isspace(*buffp))
            ++buffp;
        if(*buffp == '\0')
            continue;
        value = strtol(buffp, &p, 0);
        if(counter == DATA_MAX_SIZE){
            printf("over data max size!\n");
            break;
        } else if(p != buffp){
            data[counter++]=value;
            if(*p == '\0' || *p == '\r'|| *p == '\n')
                continue;
            buffp = p;
            goto next;
        } else {
            if(*p == '$')
                break;
            printf("format error\n");
            break;
        }
    }
    //check code 
    for(i=0;i<counter;++i){
        printf("data[%d]=%d\n",i, data[i]);
    }
    return 0;
}

<强>输出:

1 2 3
123
456
99 $
data[0]=1
data[1]=2
data[2]=3
data[3]=123
data[4]=456
data[5]=99

12345

4
$
data[0]=12345
data[1]=4