C++ 偶数、奇数、素数

C++ 偶数、奇数、素数,c++,C++,我从读取的文件中找到了偶数、奇数和素数 int _tmain(int argc, _TCHAR* argv``[]) { ifstream read; read.open("input.txt"); ofstream write; write.close(); read.close(); system("pause"); return 0; } while(getline(读取,行)){ 偶数=奇数=0; istringstream s

我从读取的文件中找到了偶数、奇数和素数

int _tmain(int argc, _TCHAR* argv``[])
{
    ifstream read;
    read.open("input.txt");
    ofstream write;

    write.close();
    read.close();
    system("pause");
    return 0;
}
while(getline(读取,行)){
偶数=奇数=0;
istringstream sRead(行);
而(sRead>>x){
如果(x%2==0){
偶数+=x;
}
如果(x%2!=0){
奇数+=x;
}
}

写问题是在迭代之间保持求和变量的状态。
避免这种情况的最好方法是声明和初始化尽可能接近其用途的变量

如果要逐行求和,请使用逐行求和:

   while (getline(read, line)){
        int even = 0;
        int odd = 0;
        int x = 0;
        istringstream sRead(line);
        while (sRead >> x){
            // ...
        }
    }

当你读新行的时候,你忘了把和重置为零吗?我真的不知道你想做什么。奇数和偶数的和是无穷大的。说真的,你必须告诉我们你想做什么,否则我们只能盲目猜测。你的代码本身就很好。我认为它把偶数行和al中的所有数字相加奇数行中的数字。其他人猜测你想得到各行的总和。这是你想要的吗?
   while (getline(read, line)){
        int even = 0;
        int odd = 0;
        int x = 0;
        istringstream sRead(line);
        while (sRead >> x){
            // ...
        }
    }