我正在撰寫一個程式,該程式需要我播種一個亂數來從 input_01.txt 到 input_10.txt 中選擇一個檔案。每個輸入檔案的第一行都有一個 6 個字符的字母系列,我必須存盤起來以備后用。出于某種原因,我從隨機種子生成的 fname 在以下操作結束時將我從檔案中讀取的 6 個字符附加到它上面。我覺得這與 %s 尋找 \0 字符有關,但不確定如何修復它:
void main()
{
srand(time(NULL));
int rng2 = 1; //(rand()%9) 1; seeding random number from 1 to 10 for input.txt set to 1 for testing, it won't generate 10 for some reason
char rng2char[2];
sprintf(rng2char, "%d.txt", rng2);
FILE *fileStream;
char letters [6];
char fname[12] = "";
printf("\nrng2 generated was %d",rng2);
if (rng2==10)
strcat(fname, "input_");
else
strcat(fname, "input_0");
strcat(fname, rng2char);
printf("\nWe have chosen %s",fname);
//below here fname is ruined
fileStream = fopen (fname, "r");
fgets (letters, 7, fileStream);
fclose(fileStream);
//somewhere above here, fname is ruined
printf("\nLETTERS ARE: %s",letters);
直到 "below here" 行,%s fname 按預期回傳 "input_01.txt"。但是,之后它回傳“input_01.txtVHAGOI”,其中 VHAGOI 是 input.txt 的第一行. 感謝您的時間和幫助。
uj5u.com熱心網友回復:
將 input.txt 的從 1 到 10 的亂數設定為 1 進行測驗,由于某種原因它不會生成 10
int rng2 = (rand()%9) 1; -> int rng2 = (rand()%10) 1;
計算所需的字符數:
char rng2char[2]; -> char rng2char[7];
我的決賽:
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
void main ()
{
// count your characters
char rng2char[7];
char letters[6];
char fname[12] = "";
int rng2;
FILE * fileStream;
srand (time (NULL));
// mod 10 rather than 9
rng2 = (rand () % 10) 1;
// no need for the if else
sprintf (rng2char, "%d.txt", rng2);
strcat (fname, "input_");
strcat (fname, rng2char);
fileStream = fopen (fname, "r");
// check for successful open
if ( fileStream != NULL)
{
fgets (letters, 7, fileStream);
fclose (fileStream);
}
else
{
printf("fopen error");
}
// debug
printf ("\nrng2 generated was %d", rng2);
printf ("\nWe have chosen %s", fname);
printf ("\nLETTERS ARE: %s", letters);
}
我的輸出,srand 10:
rng2 generated was 10
We have chosen input_10.txt
LETTERS ARE: ABCDEF
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432272.html
