0

My program is supposed to take in some input such as "Hi there." or "I have an a." (notice the ending dot) and output "yes" if the string contains an "a" or "no" if it doesn't. The problem is that cin skips whitespaces and noskipws doesn't seem to work.

The code I've got:

#include <iostream>
#include <string>
using namespace std;


int main() {
    string sequence;
    cin >> noskipws >> sequence;

    for (auto c : sequence) {
        if (c == 'a') {
            cout << "yes" << "\n";
            return 0;
        }
    }
    cout << "no" << "\n";
}

Input: "where are you."   Output: nothing
Input: "what."            Output: yes
Álvaro
  • 141
  • 2
  • 14

2 Answers2

0

Solution using getline(), as πάντα ῥεῖ suggested:

#include <iostream>
#include <string>

int main()
{
    std::string sequence;
    std::getline(std::cin, sequence);

    for (auto c : sequence) {
        if (c == 'a') {
            std::cout << "yes\n";
            return 0;
        }
    }
    std::cout << "no\n";
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
Álvaro
  • 141
  • 2
  • 14
0

You could use std::getline() or you can try this is if you want to select word by word.

#include <iostream>
#include <string>

int main(){
    std::string sequence;
    while(std::cin >> sequence){
        for (auto c : sequence) {
            if (c == 'a') {
                std::cout << "yes\n";
                return 0;
            }
        }
    }
    cout << "no" << "\n";
    return 0;
}
polmonroig
  • 937
  • 4
  • 12
  • 22