是文件中的十分之一还是偶数

时间:2019-05-21 13:05:41

标签: c++

我需要查找文件中的第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);

1 个答案:

答案 0 :(得分:1)

由于每个人对此问题都持否定态度,所以我将继续回答。 我们不能确定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;
}