gpt4 book ai didi

C 程序 - 验证从文本文件中读取的数字

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:26 24 4
gpt4 key购买 nike

我正在从一个文本文件中读取 15 个数字,每个数字在一个新行中:

1234510121314152122232426

As you can see from the code I need the numbers to be validated so they are less than 26, otherwise terminate the program.

At the moment I am validating only after inserting it to the array (numArray). Is there a cleaner way of doing it (to validate before inserting to the array)?

The problem is, I can't seem to get the actual line in the text file that's being read. That's why I've validated it using the loop index on the array (int x = numArray[i];).

Any help is appreciated, I'm quite new to C programming. Thanks.

FILE *myFile = fopen(dataset.txt, "r");
int numArray[15];

if (myFile != NULL) {

for (int i = 0; i < sizeof(numArray); i++)
{
//insert int to array
fscanf(myFile, "%d", &numArray[i]);

//Validate number
int x = numArray[i];
if (x > 25) {
printf("Invalid number found, closing application...");
exit(0);
}
}

//close file
fclose(myFile);
}
else {
//Error opening file
printf("File cannot be opened!");
}

最佳答案

当然你可以把它存储在一个局部变量中,只有在有效时才赋值。但是由于您正在调用 exit(0) 如果无效,它不会改变任何东西。我想你想从循环中break

顺便说一句,你的循环是错误的。你必须将 sizeof(numArray) 除以一个元素的大小,否则你会循环太多次,如果你的输入文件中有太多数字,你会崩溃机器(是的,我还添加了文件结束测试)

if (myFile != NULL) {

for (int i = 0; i < sizeof(numArray)/sizeof(numArray[0]); i++)
{
int x;
//insert int to array
if (fscanf(myFile, "%d", &x)==0)
{
printf("Invalid number found / end of file, closing application...\n");
exit(0); // end of file / not a number: stop
}

//Validate number
if (x > 25) {
printf("Invalid number found, closing application...\n");
exit(0);
}
numArray[i] = x;
}

//close file
fclose(myFile);
}

关于C 程序 - 验证从文本文件中读取的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39924903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com