【问题标题】:fprintf(textFilepointer) print twice into filefprintf(textFilepointer) 在文件中打印两次
【发布时间】:2015-03-10 14:24:04
【问题描述】:
#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>

FILE *textFilePointer;

int main()
{
    int counter = 0;
    int note;

    printf("Press key on Axiom MIDI keyboard to display note number\n");


    textFilePointer = fopen("/Users/jonnymaguire/Documents/Uni Work/Audio Programming /iap/iapProj/Builds/MacOSX/build/Debug/textp15.txt", "w");

    do
    {
        if(textFilePointer == NULL)
        {
            printf("!Error Opening File!");
        }
        else
        {
            /*get frequency from user*/

            note = aserveGetNote();

            fprintf(textFilePointer, "note = %d\n", note);
            fprintf(textFilePointer, "hex note = %x\n\n", note);
            counter++;


        }

    }
    while(counter < 16);

    fclose(textFilePointer);

    return 0;               /*end*/
}

这个程序只是在用户在键盘上弹奏后将音符编号打印到文件中。然而,它打印所有内容的两倍,所以我不能记录 15 个不同的音符编号和十六进制音符编号,因为它每次都写双倍,所以我只能播放 8 个。为什么?

【问题讨论】:

  • 旁注:将if(textFilePointer == NULL) 部分OUTSIDE 放在do/while 循环中(如果您不介意的话,可以添加一点点基本逻辑)。
  • 循环迭代 16 次,在每次迭代中,它将 3 个文本行写入文件:一个带有音符值,一个带有十六进制值,以及一个空行。你期待什么输出?
  • 它将音符值和十六进制值写入两次。 "注 = 67 十六进制注 = 6c 注 = 67 十六进制注 = 6c"
  • 这意味着程序结束前我只能按 8 个音符

标签: c file printf do-while


【解决方案1】:

如果您为每个演奏的音符收到 两条 消息,一条是按键,一条是释放键,您可以通过将音符消息打印到控制台来告知这一点,而不是的文件。试试这个:

#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>

int main(void) { 
    int counter = 0;
    int note;
    printf("Press key on Axiom MIDI keyboard to display note number\n");
    do
    {
        /*get frequency from user*/
        note = aserveGetNote();
        printf("note = %d\n", note);
        counter++;
    }
    while(counter < 16);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多