Home > front end >  Using cin makes my code not work properly
Using cin makes my code not work properly

Time:04-27

I'm pretty new to c and tried this project and got it to work. Basically it takes a word and a sentence then changes the word to asterisks whenever said word is found in the sentence.

The problem I am facing is I tried taking it a step further by asking the user to input a word and input a sentence and then using those as a stored variable to run the code exactly the same way as before, but this doesn't work and only outputs the first word of the sentence. I can't figure it out why it's doing that. Everything is the same except for the cin. Am I just not understanding how cin works with strings?

Main code:

#include <iostream>
#include <string>

#include "functions.hpp"

using namespace std;

int main() {

  string word = "brocolli";
  string sentence = "Roll up that brocolli. I love brocolli!";

  bleep(word, sentence);

  for (int i = 0; i < sentence.size(); i  ) {

    cout << sentence[i];

  }

  cout << "\n";

  return 0;

}

Header file:

#include <string>

void asterisk(std::string word, std::string &text, int i);

void bleep(std::string word, std::string &text);

Functions file:

#include <string>

#include "functions.hpp"

using namespace std;

void asterisk(string word, string &text, int i) {
  
  for (int k = 0; k < word.size();   k) {

    text[i k] = '*';

  }

}

void bleep(string word, string &text) {

  for (int i = 0; i < text.size();   i) {

    int match = 0;

    for (int j = 0; j < word.size();   j) {

      if (text[i j] == word[j]) {

          match;

      }

    }

    if (match == word.size()) {

      asterisk(word, text, i);

    }
    
  }

}

Adjusted main code to include cin:

#include <iostream>
#include <string>

#include "functions.hpp"

using namespace std;

int main() {

  string word;
  string sentence;

  cout << "Word: ";
  cin >> word;

  cout << "Sentence: ";
  cin >> sentence;

  bleep(word, sentence);

  for (int i = 0; i < sentence.size(); i  ) {

    cout << sentence[i];

  }

  cout << "\n";

  return 0;

}

CodePudding user response:

  cout << "Sentence: ";
  cin >> sentence;

The operator>> function you are using here stops reading at the first space character. It is not suitable for reading in a line of text.

  • Related