简体   繁体   English

将文件中的值添加到数组中,直到某个字符为止

[英]Adding values from a file to an array until a certain character

I am working on a program that uses file redirection to read in a file, read one character per line until I reach a '0', store the characters in an array , and sort that array (from largest to smallest). 我正在开发一个程序,该程序使用文件重定向读取文件,每行读取一个字符,直到达到“ 0”,将字符存储在数组中,然后对该数组进行排序(从最大到最小)。 Anyway, I really only need help with reading the characters until the zero shows up. 无论如何,我真的只需要帮助阅读字符,直到出现零为止。 Below is the text file that I am reading in: 以下是我正在阅读的文本文件:

f
k
s
j
p
a
v
r
t
u
h
m
g
e
b
y
n
z
w
l
i
x
q
c
o
d
0

Below is the code I have so far: 下面是我到目前为止的代码:

int main(void)
{
    int i=0;
    char array[100];

    while(fscanf(stdin, "%c", &array[i]) && array[i]!='0')
    {
        i++;
    }

    int N = (sizeof(array)/sizeof(array[0]));

    for(i=0;i<N;i++)
    {
        printf("%c", array[i]);
    }

return(0);
}

When I run this program, it prints out every line of the file, including the zero. 当我运行该程序时,它将打印出文件的每一行,包括零。 It also prints out some really weird characters after the zero (using gcc compiler). 它还在零之后打印出一些非常奇怪的字符(使用gcc编译器)。 What am I doing wrong? 我究竟做错了什么?

您需要将N设置为i的值,当前始终为100

You use i to keep track of how many items you've read, but then you overwrite the value of i in your loop and print out all 100 elements, whether you stored something there or not. 您可以使用i来跟踪已阅读的项目数,但是无论您是否在其中存储内容,都可以覆盖循环中i的值并打印出所有100个元素。

Use different variable for counting the element than you do for looping, and use the count as your loop limit. 使用与循环不同的元素来计数元素,并将计数用作循环极限。

int count=0;
char array[100];

while(fscanf(stdin, "%c", &array[count]) && array[count]!='0')
{
    count++;
}

for(i=0;i<count;i++)
{
    printf("%c", array[i]);
}

fscanf needs to skip the separator (enter or space), else it will be incorporated into your list. fscanf需要跳过分隔符(输入或空格),否则它将被合并到您的列表中。 Adding a space fixes that. 添加空格可以解决此问题。

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

int sort (const void *a,const void *b)
{
    return ((int)*((unsigned char *)a)) - ((int)*((unsigned char *)b));
}

int main (void)
{
    unsigned char array[100],i=0;
    while (fscanf(stdin," %c", &array[i]) && array[i] != '0')
        i++;
    qsort (array,i,1,sort);
    while (i)
        printf ("%c\n", array[--i]);
}

It may seem this program sorts the wrong way around but the printing loop also happens to print in reverse, so that solves it neatly. 看来该程序的排序方式有误,但打印循环也恰好反向打印,因此可以很好地解决它。 As the array is unsigned char, the sort routine casts this to int to prevent possible overflow. 由于数组是无符号字符,因此排序例程将其强制转换为int以防止可能的溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM