gpt4 book ai didi

C - 将值返回给 main

转载 作者:行者123 更新时间:2023-12-02 22:08:30 25 4
gpt4 key购买 nike

没有找到任何可以回答我的问题的东西,所以这里是:

我想从一个函数返回一个整数到我的 main 以供进一步使用,具体来说,它是一个 add() 函数,它根据文本文件中的条目创建一个列表。我要返回的整数称为错误,在函数开头声明为 0 并在满足条件时更改为 1 (在我的例子中,如果有的话找到 a-z、A-Z、- 和 ' ' 以外的字符)。如果满足此条件,我想将错误(如 1)返回给主函数,否则我将其作为 0 返回。在我的 main 中,我有一个 if 语句来检查错误是否为 1,然后打印一条错误消息并返回 1。这可能吗?我已经尝试了一些东西,但它不起作用,如果我在我的 main 中将错误变量初始化为 0,那么在出现错误情况时,add 函数不应该将它更改为 1 吗?我不想使用全局变量,只想将 add 函数实现到 main 中作为最后的手段。

对不起,如果这完全是废话,我是一个初学者。

int add(char line[])
{
struct node *newnode = (struct node *) malloc(sizeof(struct node));
struct node *walker = newnode;

strcpy(newnode->name, line);

int check = 0;
int error = 0;

while(line[check] != '\n')
{
if(line[check] == '!')
{
error = 1;
return error;
}
check++;
}
. //Here is just the creation of the list elements
. //If the functions reaches end, it returns error with 0 as value
.
}

还有主要的:

int main()
{
FILE *fp;
char line[33];
int error = 0;

fp = fopen("test.txt", "r");

if(!fp)
{
printf("Error.");
return 0;
}

while(fgets(line, 33, fp) != NULL)
{
add(line);
}
fclose(fp);

if(error == 1)
{
printf("error");
return 1;
}

// ...
}

编辑:好的,我已经成功了,因为一些人基本上为我提供了正确的解决方案,我想在这里说声谢谢!不知道我是否可以选择多个答案是正确的。

最佳答案

您似乎有两个名为error 的变量,一个在add() 中,另一个在main() 中,它们是不同的变量!你至少需要改变

add(line);

error = add(line);
if (error != 0)
break;

关于C - 将值返回给 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15742685/

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