将字符串传递到scanf

问题描述 投票:0回答:1

我正在尝试制作一个程序,该程序会在给定用户输入的情况下生成一个字符串,然后将该字符串传递给一个函数,该函数会将stdin更改为虚拟文件,将该字符串写入该文件,在该文件上使用scanf,然后删除文件,但是我在将stdin重定向到虚拟文件时遇到麻烦,有关仅能扩展到函数范围的最佳操作的任何帮助?

int scan(const char* __restrict__ _format, ...){
    FILE* original = stdin, *mod = calloc(1, sizeof(FILE));
    mod = freopen("testFile.txt", "w+", stdin);
    fputs(_format, stdin);
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%d, %d", a, b);
//    freopen(orig)
    return 1;
}

void swap(char* a, char* b) {
    if (*a != ' ' && *b != ' ') {
        char temp = *a;
        *a = *b;
        *b = temp;
    }
}

void permiate(char* str, int start, int end){
    int i;
    if(start == end){
        printf("%s\n", str);
    }else{
        for(i = start; i<=end; i++){
            swap(str+start, str + i);
            permiate(str, start + 1, end);
            swap(str + start, str + i);
        }
    }
}

int main(){
    int a, b;
    char str[]  = "1 3";

    //function to put string to stdio
    scan(str);
    scanf("%d %d", &a, &b);
    printf("%d, %d", a, b);
    return 0;
}

[有人指出fscanf之后,由于我的老师从未涉及过它,所以我从未意识到它的功能,我找到了扫描功能的可行解决方案:

int scan(const char* __restrict__ _format, ...){
    int *a = malloc(sizeof(int)), i = 0;
    FILE *fp1 = fopen("testfile.txt", "w");
    fputs(_format, fp1);
    freopen("testFile.txt", "r", fp1);
    while(fscanf(fp1, "%d", &a[i]) != EOF){
        i++;
        a = realloc(a, sizeof(int)*i);
    }
    for(int j = 0; j < i; j++){
        printf("%d, ", a[j]);
    }
    fclose(fp1);

    return 1;
}

但是无论何时我给str一个像“ 1 2 3 4 5 6 ...”之类的值或具有5个以上数字的任何东西,如果我保留realloc,则第5个数字始终为0,如果我注释掉该行,则没事。有什么想法吗? ps我在uni的实验室仅了解数组的基本用法,没有动态内存或其他任何东西,因此,如果im使用任何错误,它将得到极大的应用

c file scanf stdin
1个回答
0
投票

[好的,我想我了解您正在尝试做的事情,而且这是可行的,但我当然不建议这样做。每当您freopen()标准流之一时,就没有portable

© www.soinside.com 2019 - 2024. All rights reserved.