甚至是文件中的每个第十个数字,甚至是奇数

is every tenth number in file even or odd

本文关键字:十个数字 文件      更新时间:2023-10-16

我需要在文件中找到每个第10个数字,并定义数字是否偶数或奇数

我只记得如何读取文件,不知道下一步该怎么做

string linia;
fstream plik;
plik.open("przyklad.txt", ios::in);
if(plik.good() == true)
{
    while(!plik.eof())
    {
        getline(plik, linia);
        cout << linia << endl; 
    }
    plik.close();
}   
system("PAUSE");
return(0);

由于每个人都对这个问题是如此负面,所以我要继续回答。我们不能确定OP是从正确来源学习的,正如他所说,他不记得下一步该怎么做,这意味着他真的没有选择。

带有一些解释评论的工作代码如下:

#include <iostream>
#include <fstream>
using namespace std;
// Returns wether the number is odd
bool isOdd(const int num){
    return num % 2 != 0;
}
int main(){
    // Open the file in input mode
    ifstream inputFile("data.txt");
    int count(0); // Represents the current line number we are checking
    string line;  // Represents the characters contained in the line we are checking
    // The loop goes over ever single line
    while(getline(inputFile, line)){
        //Increase the line count by 1
        ++count;
        //If the line we are on is either 0 (not possible due to instant increment), 10, 20, 30, ...
        if(count % 10 == 0){
            //Get the number (not safe since it's not guaranteed to be a number, however it's beyond the scope of the question)
            int number = stoi(line);
            //Ternary statement can be replaced with a simple if/else
            cout << "The number " << number << " is " << (isOdd(number) ? "odd" : "even") << 'n';
        }
    }
    return 0;
}