问题
I am a complete beginner in C++, and am trying to do the following program:
- Read a sentence from the console.
- Break the sentence into words using the space character as a delimiter.
- 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