簡體   English   中英

有沒有一種方法可以使用 while 循環將文件中的元素掃描到數組中?

[英]Is there a method to scanf elements from a file into an array using a while loop?

我試圖讓 void getMessage() 從 msgfile.txt 讀取消息,一次一個元素。 msgfile.txt 有 26 個 integer 數字。 我正在使用一個while循環來讓每個integer(總共26個)以與“void getCode()”類似的方式讀取,除了使用while循環而不是for循環,但我擁有它的方式是while循環跟隨一個for循環。 這沒有正確執行。

這是在 msgfile.txt 中找到的輸入,除了它不是在一行中,而是在列中:

19546 14501 17309 13027 16149 21512 18035 14014 15700 12515 16514 18207 13407 14837 16842 21037 15333 13244 21224 16321 14146 16014 20727 12804 18811 13711

預期的 output 是包含 msgfile.txt 元素的數組“numbers[26]”:

數字[0]:19546 數字[1]:14501 等。

#include <stdio.h>
# define LISTNUM 26

void getCode();
void getMessage(int n, int numbers[LISTNUM]);
//void sortMessage();
//void decodeMessage();

int main( void ) {
    
    
    int n,i;
    int numbers[LISTNUM];
    
    
    FILE *fp;
    fp = fopen( "msgfile.txt", "r" );
    if( fp == NULL )
    {
        printf( "could not open msgfile.txt\n" );
        return 1;
    }

    while( !feof( fp ) )
    {
        fscanf( fp, "%d\n", &n );
        printf( "%d\n", n );
    }
    
    
        getCode();
        getMessage(n,numbers);
        //sortMessage();
        //decodeMessage();
}
        
    
    
    
    
void getMessage(int n, int numbers[LISTNUM])
{
    
    fopen_s(fopen, "msgfile.txt","r");
    
    while(!feof(fopen))
    {
        for(int i = 0; i < LISTNUM; i++)
        {
            scanf(fopen,"%d", &numbers[LISTNUM]);
        }
    }
}

void getCode()
    {
        FILE *filepointer2;
        
        char character[52];
        
        /*step 2: open codefile.txt and read from it*/
        
        filepointer2 = fopen("codefile.txt", "r");
        
        if (filepointer2 == NULL)/*if file does not open*/
        
        {
        
        printf("Can't open file for reading.\n");
        
        }
        
        else
        
        {
        
        /*if file opens read the characters into the array*/
        
        for(int i=0;i<52;i++){
        
        fscanf(filepointer2, "%c", &character[i]);
        
        }
    }

&numbers[LISTNUM] in scanf(fopen,"%d", &numbers[LISTNUM])看起來很可疑。 將其替換為&numbers[i]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM