Adding some debug output to the code shows a couple of issues:
- The first
for
loop reads in n+1
strings, while we are expecting the user to enter only n
strings. The second for
loop also prints n+1
strings, although that's not a problem, because the vector contains n+1
elements.
- Due to mixing both
std::cin >>
and std::getline
for reading user input, the first string read with std::getline
is empty. You would need whether to:
- use
std::getline
for all the user input readings (and, for n
, convert the string to a number), or
- flush the input buffer with
cin.ignore
after the std::cin >>
, as explained in this answer.
The code below fixes those two issues and adds some debug output (it also follows a few best practices such as, not using namespace std;
, defining variables next to their first use, value-initializing local variables, and using block braces even for one-line blocks).
[Demo]
#include <iostream> // cin, cout
#include <limits>
#include <string> // getline
#include <vector>
int main() {
int n{};
std::cout << "n: ";
std::cin >> n;
std::cout << n << "\n\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::vector<std::string> vec{};
for (int i = 0; i < n; i++) {
std::cout << "Enter a string: ";
std::string item{};
std::getline(std::cin, item);
std::cout << "item: " << i << ": '" << item << "'\n";
vec.push_back(item);
}
std::cout << "\n";
for (auto& of : vec) {
std::cout << "'" << of << "': ";
if (of.find("ba") != std::string::npos) {
std::cout << "false\n";
} else {
std::cout << "true\n";
}
}
}
// Outputs:
//
// n: 5
//
// Enter a string: item: 0: 'aabbb'
// Enter a string: item: 1: 'ba'
// Enter a string: item: 2: 'aaa'
// Enter a string: item: 3: 'b'
// Enter a string: item: 4: 'abba'
//
// 'aabbb': true
// 'ba': false
// 'aaa': true
// 'b': true
// 'abba': false
For this particular case, you could also use std::is_partitioned
. This algorithm tells you if all the elements of a range that satisfy a given predicate appear before all the elements that don't (see here). The predicate would check if a character is equal to 'a'
.
[Demo]
#include <algorithm> // is_partitioned
#include <cstring> // strlen
#include <fmt/core.h>
int main() {
for (auto&& s : { "aabbb", "ba", "aaa", "b", "abba" }) {
fmt::print("'{}': {}\n", s, std::is_partitioned(s, s + strlen(s),
[](unsigned char c) { return c == 'a'; }));
}
}