C++ 'Using space as a delimiter' [closed]

江枫思渺然 提交于 2019-12-14 00:10:31

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/18597850/c-using-space-as-a-delimiter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!