我目前正在编写一个程序,它接收一个未知数量的双精度数,每个双精度数都来自一个文本文件。它应该将这些元素放入数组中,但它不起作用。我的打印循环工作,但它只打印零。在来到这里之前,我已经尝试了很多东西并且查了很多。这是我的代码。
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Open an file to read from
FILE *file;
file = fopen("data.txt","r");
if (file == NULL)
{
printf("File not found.");
return -1;
}
//Count the number of lines in the input file
int numLines = 0; //CHANGE TO 1 ???
int ch;
do
{
ch = fgetc(file);
if (ch == '\n')
numLines++;
} while (ch != EOF);
//Put all of the data read into an array;
double input[numLines];
int i = 0;
while ((fscanf(file, "%lf\n", &input[i])) == 1)
i++;
//Close the file
fclose(file);
//Test printing elements of array
for (i = 0; i < numLines; i++)
printf("%lf\n", input[i]);
return 0;
}
答案 0 :(得分:0)
OP对 @Effect()
selectAndLoadStore$: Observable<Action> = this.actions$
.ofType(storeActions.SELECT_AND_LOAD_STORE)
.withLatestFrom(this.store.select(ngrx.storeState))
.map(([action, storeState]) => [action.payload, storeState])
.switchMap(([storeName, storeState]) => {
const existsInStore = Boolean(storeState.urlNameMap[storeName]);
return Observable.if(
() => existsInStore,
Observable.of(new storeActions.SetSelectedStore(storeName)),
this.storeService.getByUrlName(storeName)
.map(store => new storeActions.LoadSelectedStoreSuccess(store))
);
});
@Effect()
selectAndLoadStore$: Observable<Action> = this.actions$
.ofType(storeActions.SELECT_AND_LOAD_STORE)
.withLatestFrom(this.store.select(ngrx.storeState))
.map(([action, storeState]) => [action.payload, storeState])
.switchMap(([storeName, storeState]) => {
const existsInStore = Boolean(storeState.urlNameMap[storeName]);
let obs;
if (existsInStore) {
obs = Observable.of(new storeActions.SetSelectedStore(storeName));
} else {
obs = this.storeService.getByUrlName(storeName)
.map(store => new storeActions.LoadSelectedStoreSuccess(store));
}
return obs;
});
结果的测试好,但代码不检查文件中是否有太多数字。
fscanf()
然后代码忽略了while ((fscanf(file, "%lf\n", &input[i])) == 1)
i++;
的最后一个值,而是打印i
次,即使成功扫描的次数较少。
numLines
结束代码应该是
for (i = 0; i < numLines; i++)
printf("%lf\n", input[i]);
这会打印0行!该文件需要重置为第二次传递。 @paulr
while (i < numLines && (fscanf(file, "%lf\n", &input[i])) == 1)
i++;
for (j = 0; j < i; j++)
printf("%lf\n", input[j]);
另一个问题是假设rewind(file);
while (i < numLines && (fscanf(file, "%lf\n", &input[i])) == 1)
...
的计数与数字计数相同。如果每行有多个数字,或者最后一行有一个数字但没有'\n'
,这很容易被愚弄。
一个简单的解决方法是使'\n'
1更大,并使用实际扫描成功计数作为要打印的数字计数。更健壮的代码将使用input[]
一次读取1行,并包含其他错误检查。