从输入复制到输出文本文件

Copying from input to the output text file

本文关键字:文本 文件 输出 输入 复制      更新时间:2023-10-16

嗨,这是我的功能代码,但是它不能正常工作,它应该从input.txt上读取数字,并计算每行中的奇数总数,然后在每行中的奇数,然后质量数字的连接(确实正确),还将所有素数的数字复制到输出。txt

这是我的代码,问题是:它还复制不是质数的数字。非常感谢!!!

#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream read;
    read.open("input.txt");
    ofstream write;
    write.open("output.txt");
    string line;
    int even, odd, primeXprime;
    if(read.fail())
        cout << "Cant open input.txt" << endl;
    int x, p = 0;
    if(read.is_open())
    {
        while(read, line)
        {
            even = odd = 0;
            primeXprime = 1;
            istringstream sRead(line);
            while(sRead >> x)
            {
                if(x % 2 == 0)
                    even += x;
                if(x % 2 != 0)
                    odd += x;
                for(int i = 2; i <= x; i++)
                {
                    if(x % i == 0)
                        p++;
                    if(p == 2)
                    {
                        primeXprime *= x;
                        write << x << " ";
                        p = 0;
                    }
                    else
                        break;
                }
            }
            cout << "Sum of even numbers are: " << even << endl;
            cout << "Sum of odd numbers are: " << odd << endl;
            cout << "Sum of prime numbers are: " << primeXprime << endl;
            cout << endl;
        }
        read.close();
        write.close();
        system("pause");
        return 0;
    }
}

问题是在您的原始测试算法中,直到将数字除以将其除以范围内的所有数字[2,sqrt(n)]

在" "中,如果(p == 2)"您假设它不会在范围内以后将其除以任何数字。

替换整个循环
for(int i = 1; i < x; i++)
{
               if(x % i == 0)
                    p++;
}
if(p < 2)
{
    primeXprime *= x;
    write << x << " ";
}
p = 0;