0

I am working on a trivial problem, but I cant figure it out. The program should put out the part after "simon says" if the beginning of str1 is "simon says". if i run it like in the following code, it works, but if i enter the string over cin >> str1; myself, it doesnt. Does anybody have a tip for me? (and yes, this is a kattis problem)

int main() { string str1("simon says write a program"); //cin >> str1; string str2 ("simon says"); if (str1.compare(0,10,str2,0,10) == 0){ cout << str1.substr(11,str1.size()); } return 0; } 
5
  • 1
    Use std::getline() cin reads strings word wise. Commented Jul 21, 2015 at 12:23
  • 1
    >> extracts whitespace-separated tokens. This is not the construction you are looking for. Commented Jul 21, 2015 at 12:23
  • oh god im so dumb. thank you. i completely forgot that Commented Jul 21, 2015 at 12:24
  • You should print str1 after cin << str1, you can see that the string contains only simon. Commented Jul 21, 2015 at 12:25
  • I think you have got the answer you are looking for. So why don't you close the question. Commented Jul 21, 2015 at 12:26

2 Answers 2

4

It's because std::cin gets whitespace-separated strings. If you will try to read a string from the standard input using

std::cin << str1; // something here std::cin << str2; 

And you will enter "simon says", "simon" will land in the str1 and "says" will go to the str2. To read a whole line you should use

std::getline() 
Sign up to request clarification or add additional context in comments.

Comments

1

With using cin >> str1, if you print str1 for the sentence "Simon write something", you will see that str1 has the value "Simon".

To not cut the sentence to the first space, Replace cin >> str1 by getline(cin, str1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.