如何退出 while(scanf_s...) 循环?

How do I quit a while(scanf_s...) loop?

我的 Visual Studio 告诉我使用 scanf_s(),现在我已经使用了它,我的 while 循环将永远持续下去。假设我正在阅读行,其中每行都有两个数字,用 space 分隔。一旦我输入了所有数字,我的 while 就不会停止。如何退出循环?

int main() {
    
    int i,j;
    while (scanf_s("%d %d", &i, &j)) {
        int maxLength = 0;
        for (int index = i; index <= j; index++) {
            int tmp = cycle(index);
            if (tmp > maxLength) {
                maxLength = tmp;
            }
        }
        printf("%d %d %d\n", i, j, maxLength);
    }
    
    cout << "lol";
    return 0;
}

scanf_s returns 成功翻译的字段数。出错时 return 为 0EOF.

您的逻辑假设任何 non-zero 值都是成功的。当 return 值为 EOF 时,该假设失效。

尝试与您需要的字段数进行比较:

while (2 == scanf_s("%d %d", &i, &))

My Visual Studio tells me to use scanf_s,

可疑的建议,但在 MS-land 中是标准的(作为 scanf 的替代)。

and now that i've used it my while goes on forever.

这不是 scanf_sscanf 之间的区别。 return 成功转换和分配的字段数。两者都将无限期地等待输入,直到他们看到 non-matching 数据或文件末尾。 return EOF 均非零 ,当到达文件末尾时未扫描任何字段。

Let's say i'm reading lines, where each line has to numbers seperated with a space. Once ive inserted all the numbers my while never stops. How do i quit my loop?

测试特定的预期 return 值,而不是其一般真实性:

    while (scanf_s("%d %d", &i, &j) == 2) { // ...

如果您正在阅读常规文件,那么这本身就足够了,但如果您正在阅读无限量的交互式输入,那么您必须依靠用户提供某种他们没有更多的指示器提供。他们可以发送 end-of-file 信号( 在 Windows 上),或者在这种情况下,他们还可以输入包含既不是空格也不是十进制数字或'+' 或 '-'(在输入中将保持未读状态)。