-5

I am a complete beginner in C++, and am trying to do the following program:


  1. Read a sentence from the console.
  2. Break the sentence into words using the space character as a delimiter.
  3. Iterate over each word, if the word is a numeric value then print its value doubled, otherwise print out the word, with each output on its own line.

I am really lost on how to do this. Especially using the space key as a delimiter.

In silico
  • 51,091
  • 10
  • 150
  • 143
Shiv Aiyar
  • 1
  • 1
  • 1
  • 1
  • 2
    Due to the lack of info, I will have to ask: you know what is a string? If so, are you familiar with C++ strings? If not, I suggest you to make some reads before coding this program. – Natan Streppel Sep 03 '13 at 17:15
  • If you're familiar with processing strings in general, then look at `gets` and `strtok`. – lurker Sep 03 '13 at 17:16
  • Try searching for a tokenizer. You've shown no attempts or shown that you did any research before hand. If you can't do part 1, then you really haven't tried anything, but for part two, look up tokenizing. – CamelopardalisRex Sep 03 '13 at 17:16
  • Possible duplicate of http://stackoverflow.com/questions/236129/splitting-a-string-in-c – Lawrence H Sep 03 '13 at 17:21

1 Answers1

3

Can have something like following :

With std::stringstream and std::getline

std::string str;
std::string temp;
std::getline(std::cin,str);

std::stringstream ss(str);

while(getline(ss,temp, ' ')) // delimiter as space
{
      std::stringstream stream(temp);
      if(stream >> val)
        std::cout<<2*val<<std::endl;
      else 
        std::cout<<temp<<std::endl;
}

See DEMO

P0W
  • 46,614
  • 9
  • 72
  • 119
  • Might want to add protection against "numbers" like 100xxx; e.g. `char x; ... if ((stream >> val) && !(stream >> x)) {...}` – anatolyg Sep 03 '13 at 17:38