Problem mit fscanf

Nord-Süd-Richtung

Erfahrenes Mitglied
Hi Leute

ich möchte gerne aus einer Datei die Auflösung für mein Programm auslesen. Es wird dort in dieser Form gespeichert:
active_resolution: 1
Meine Ansätze:
C++:
void get_resolution(int &width, int &height){
  FILE* file;
  if( (file = fopen("./data/resolution.game","w+")) == NULL ){
    game_shutdown();
  }
  short resolution,match;
  if( fscanf(file,"%d",&resolution) <= 0 ){
    fprintf(file,"%","active_resolution: 1");
    resolution = 1;
  }
  fclose(file);

Resolution enthält nicht wie gewünscht 1, sondern den maximalen Wertebereich von short (ich vermute weil es ohne Wert initialisiert wird). Wir kann ich denn nun den Wert aus der Datei auslesen?
 
Hi.

Wenn dort in der Datei "active_resolution: 1" drin steht wie du sagst, dann kannst du doch das nicht als Integer einlesen?! :confused:

Im Grunde kannst du es genau so einlesen, wie du es auch geschrieben hast (außer das du %hd verwenden mußt):
C:
if (fscanf(file, "active_resolution: %hd", &resolution") == 1) {
  ...
}
Gruß
 
Hi

das hat leider nicht funktioniert. Auch folgendes klappt nicht, die Fenstergröße beträgt immer 40x40 (Kontrollgröße)
C++:
short resolution = 0;
  char buffer[50];
  if( fscanf(file,"%s %d",&buffer,&resolution) != 1 ){
    fprintf(file,"%s","active_resolution: 1");    
    resolution = 2;
  }
  fclose(file);
  if( resolution == 1 ){
    width = 640;
    height = 480;
  }
  if( resolution == 2 ){
    width = 40;
    height = 40;
  }
 
das hat leider nicht funktioniert.
Weil du es falsch anwendest. Warum liest du dir denn nicht mal die Dokumentation der fscanf Funktion durch?

Die Funktion gibt die Anzahl der erfolgreichen Konvertierungen zurück - bei dir also 2 (wenn es erfolgreich war).

Wie gesagt, du mußt %hd verwenden wenn du short nimmst.

Außerdem kannst du auch die Zuweisung einer Konvertierung überspringen, wenn du den Wert gar nicht brauchst:
C:
if (fscanf(file, "%*s %hd", &resolution) == 1) {
  ..
}
Gruß
 
Hi

ich habe dort schon alles durchprobiert, auch a+...nur ich erhalte dann immer die Windows(!) Fehlermeldung: Dieses Programm funktioniert nicht mehr... Bevor überhaupt das Fenster zusehen ist.

C++:
//Hier nochmal die komplette Funktion (jetzt geändert und es funktioniert, danke :) )
void get_resolution(int &width, int &height){
  FILE* file;
  if( (file = fopen("./data/resolution.game","r+")) == NULL ){
    game_shutdown();
  }
  short resolution = 0;
  if( fscanf(file,"%*s %hd",&resolution) != 1 ){
    fprintf(file,"%s","active_resolution: 1");    
    resolution = 2;
  }
  fclose(file);
  if( resolution == 1 ){
    width = 640;
    height = 480;
  }
  if( resolution == 2 ){
    width = 40;
    height = 40;
  }
}
 
Zuletzt bearbeitet:
Zurück