【问题标题】:Not all code executes, but program exits properly并非所有代码都执行,但程序正确退出
【发布时间】:2013-12-01 22:21:57
【问题描述】:

这是一个程序,它应该找到低于某个 max 值的循环素数。它适用于max<=1000,但如果是max=10000,程序结束时不会出错,但不会将最后两行打印到控制台,即使它总是应该打印。它也不再打印任何圆形素数,但这可能是我的算法问题,我稍后会担心。

注意:我使用的是 MVS 2010,在cout 之前有不必要的std::,因为它有时会说 cout 是模棱两可的。

using namespace std;

int main(){

    const int max = 10000;
    int nrOfPrimes = 0;
    int* primes = findIfPrimes(max);
    for(int i = 2; i < max; i++){
        //check if number is prime
        if(primes[i] == 0){
            nrOfPrimes++;
            int l = 0;
            int* permutations = findPermutations(i, l);
            //variable saying lf all permutations are prime
            bool allPrime = true;
            //check all permutations, if they are not prime change allPrime
            for(int j = 0; j < l; j++){
                if(primes[permutations[j]] != 0){
                    allPrime = false;
                    break;
                }
            }
            //if it wasnt circular prime- continue
            if(allPrime == false)
                continue;
            //if it was circular prime, change all permutations to "circular prime"
            std::cout << "Circular primes: ";
            for(int j = 0; j < l; j++){
                primes[permutations[j]] = 2;
                std::cout << permutations[j] << " " << endl;
            }
            std::cout << endl;
        }
    }

    //find total count
    int result = 0;
    for(int i = 2; i < max; i++)
    if(primes[i] == 2)
        result++;
    std::cout << "total number of primes " << nrOfPrimes << endl;
    std::cout << "total number of circular primes " << result << endl;
    return 0;
}

【问题讨论】:

  • 刷新你的输出缓冲区。
  • @HotLicks 它有效,但 std::endl 不应该也刷新 cout 吗?
  • 自从我搞砸了 cout 东西已经有十几年了,但是 IIRC 你只有在你做 cin 时才会自动刷新 cout 缓冲区。

标签: c++ std


【解决方案1】:

return 0 放在main() 之前:

bool fail = cout.fail();
cout.clear();
cout << fail << endl;
cin.ignore(cin.rdbuf()->in_avail()); // clears all remaining input
cin.get(); // waits for ENTER

fail 的含义是什么?

fail = cout.good(); 执行相同操作。那说明什么呢?

【讨论】:

  • 0 代表两个,在每个圆形素数之后没有和带有“cout.flush()”的代码。
  • @Xyzk:即使 max
  • 那我就不知道了。也许 cout 的这种歧义存在问题。我使用 VC2010 并且从来没有遇到过这个问题。是的,endl 应该刷新 - 在没有任何手动刷新的情况下尝试 std::cout &lt;&lt; std::endl;
  • 无论如何都要寻求帮助:)
猜你喜欢
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多