How do I continue with this question

Write a function that reads all lines of the input, and print the number of lines that are exactly equal to the first line (including the first line itself).

Input Format
There will be a maximum of N lines
Each line will contain M characters, consisting only of alphanumeric characters.
The last line may or may not have a newline(\n) at the end.

Constraints
0 < N <= 1000
0 <= M <= 100

Note: N will not be explicitly given as an input, you may read the input until EOF is reached.

Output Format:
A single integer

Sample Input:
First line
2nd line

The line above is empty
First line
FIRST LINE
FIRST LINE
Last Line

Sample Output:
2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    string x[1000];
    string y1;
    int z;
    for(int i = 1; i <= 1000; i++)
    {
        getline(cin,x[i]);
        //cout << x[i] << "\n";
        
        
            
        
    }
    
}
Unless I'm missing something, this is very easy.
You certainly don't need an array of strings.
Just save the first line in a string (call it first) and set your count to 1 (N is guaranteed to be at least 1, apparently, so there will always be a first line).
Then read the rest of the lines one at a time into a different string (you could call it line).
If line == first, increment count.

1
2
3
4
5
6
7
8
9
10
string first, line;
int count = 1;

getline(cin, first); // read first line and store it for comparison

// This is how you read lines until the end of the file:
while (getline(cin, line))
{
    ...
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main() {
	std::string first;
	size_t cnt {!!std::getline(std::cin, first)};

	for (std::string line; std::getline(std::cin, line); cnt += line == first);

	std::cout << "There are " << cnt << " lines the same as line 1\n";
}

Registered users can post here. Sign in or register to post.