简体   繁体   English

只获取没有 printf 的返回值

[英]Get only return value without printf

I'm writing a program for a college assignment and one of the required functions needs to conditionally print a value and then return either 1 if it printed a value or 0 if it didn't print a value.我正在为大学作业编写一个程序,其中一个必需的函数需要有条件地打印一个值,然后如果它打印一个值则返回 1,如果它没有打印一个值则返回 0。 In another required function, I have an array of values that may or may not be printed.在另一个所需的 function 中,我有一个可能会或可能不会打印的值数组。 If any single one of those values are not printed, all of them must not be printed.如果没有打印这些值中的任何一个,则不得打印所有这些值。 The problem is, I need to check through the array to see if any of them will not be printed using the first function.问题是,我需要检查数组以查看是否使用第一个 function 不会打印其中的任何一个。 It wouldn't be a problem if the first value in the array will not be printed, but if the first few will be printed and then one of them won't be, it prints the first few while checking if any won't be printed, thus not meeting the requirements.如果数组中的第一个值不会被打印,这不会是一个问题,但是如果前几个将被打印,然后其中一个不会被打印,它会打印前几个,同时检查是否有任何一个不会被打印打印出来的,不符合要求。

I know that was kind of confusing so here's some pseudocode:我知道这有点令人困惑,所以这里有一些伪代码:

short function1(value) {
    short retVal = 0;
    if (valueIsGood) {
        printf(value);
        retVal = 1;
    }
    return retVal;
}

short function2(array[]) {
    int i;
    for (i = 0; i < sizeof(array); i++) {
        if (function1(array[i]) == 0) {
            return "invalid";
        }
    }
}

If the array has values { goodValue1, goodValue2, badValue1, goodValue3 }, it prints goodValue1 and goodValue2 before returning invalid.如果数组有值 { goodValue1, goodValue2, badValue1, goodValue3 },它会在返回无效之前打印 goodValue1 和 goodValue2。 I want a way for it to just return invalid.我想要一种方法让它返回无效。 Thanks.谢谢。

Think in a way of switching on/off a flag.以打开/关闭标志的方式思考。 Since it's an assignment, I will show you the algorithm in pseudo code only.由于这是一项作业,我将仅以伪代码向您展示算法。

In first case the pseudo-code is:在第一种情况下,伪代码是:

set flag off
for each line
    if line is printable
        print line
        set flag on
    endif
endfor
if flag is on
    return 1
else
    return 0
endif

So now this will help you to construct the second function所以现在这将帮助您构建第二个 function

set flag on
for each line
    if line is not printable
        set flag off
    endif
endfor
if flag is on
   for each line
      print line
   endfor
else
    return 0
endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM