简体   繁体   English

<iostream> std:cout函数内没有打印(FIXED:for for issue issue)

[英]<iostream> std:cout within function not printing (FIXED:for loop issue)

NEVERMIND, FIXED IT. NEVERMIND,固定它。 for loop issue for循环问题

I'm trying to do some number crunching with formatted output, and I've run into a problem with half my output not printing. 我正在尝试使用格式化输出进行一些数字运算,并且我遇到了一个问题,我的输出有一半没有打印。 I've written a small test code to illustrate the problem: 我写了一个小测试代码来说明问题:

#include <iostream>

int testF(){
    for (int i; i<10; i++) {
        std::cout << i << "\n";
    }
    return 0;
}

int main(){
    std::cout << "START_(this_line_seems_to_be_causing_problems)\n";
    int sret = 1;
    sret = testF();
    std::cout << sret << "\n";
    std::cout << "END\n";
    return 0;
}

The problem seems to hinge on the line std::cout << "START_(this_line_seems..." . If I comment out this line, it will print the contents of testF() . If I don't then testF() does not print, although it does give a return value. 问题似乎取决于行std::cout << "START_(this_line_seems..." 。如果我注释掉这一行,它将打印testF()的内容。如果我不这样,那么testF()会不打印,虽然它确实给出了返回值。

It's important that I can print from both main and my functions. 重要的是我可以从main功能和我的功能进行打印。 Is there a way I can do both? 我有办法做到这两点吗?

try initializing i: 尝试初始化我:

int testF(){
for (int i = 0; i<10; i++) {
    std::cout << i << "\n";
}
return 0;
}

and why int sret = 1; 为什么int sret = 1; // value is never used or passed into function //值永远不会被使用或传递给函数

all you want is: 你想要的只是:

int sret;
sret = testF();
std::cout << sret << "\n";
std::cout << "END\n";

also why doing 也为什么这样做

 sret = testF(),

 cout<<sret 

this will just append 0 to your output, instead call testF() directly. 这只会将0附加到输出,而是直接调用testF()。

 for (int i; i<10; i++) { 

This loop tries to read from an uninitialised int . 此循环尝试从未初始化的int读取。 That's undefined behaviour , which means everything can happen and that the program may behave strangely. 这是未定义的行为 ,这意味着一切都可能发生,程序可能会表现得很奇怪。

What probably happens here in practice is that the memory location of the uninitialised variable contains some random data which is interpreted as something greater than 10, and that the random data is somehow affected by the previous std::cout statement. 在实践中可能发生的事情是,未初始化变量的内存位置包含一些随机数据,这些数据被解释为大于10的内容,并且随机数据以某种方式受到先前std::cout语句的影响。 But that's just guessing; 但那只是猜测; the C++ language simply does not define how your program behaves. C ++语言根本不定义程序的行为方式。

In order to avoid undefined behaviour, you must initialise the variable: 为了避免未定义的行为,您必须初始化变量:

for (int i = 0; i<10; i++) {

By the way... 顺便说说...

 int sret = 1; sret = testF(); std::cout << sret << "\\n"; 

This can be written more concisely as: 这可以更简洁地写成:

std::cout << testF() << "\n";

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

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