C++ C++;stringstream,若单词是数字,则除以2

C++ C++;stringstream,若单词是数字,则除以2,c++,stringstream,C++,Stringstream,我对编程相当陌生,必须创建一个程序来读取提示:“我有8美元要花。”然后需要将每个单词打印在单独的一行上,如果任何字符串是数字,则需要将其除以2。因此,最终应打印为: I have 4 dollars to spend. 我已经设法做了所有的事情,除了找到数值并将其除以2。到目前为止,我有: #include <iostream> #include <string> #include <sstream> using names

我对编程相当陌生,必须创建一个程序来读取提示:“我有8美元要花。”然后需要将每个单词打印在单独的一行上,如果任何字符串是数字,则需要将其除以2。因此,最终应打印为:

I
have
4
dollars
to
spend.
我已经设法做了所有的事情,除了找到数值并将其除以2。到目前为止,我有:

    #include <iostream>
    #include <string>
    #include <sstream>

    using namespace std;

    int main()
    {
string prompt;
string word;

cout << "Prompt: ";

getline(cin, prompt);

stringstream ss;
ss.str(prompt);

while (ss >> word)
{
cout << word << endl;
}

return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串提示;
字符串字;
cout>word)
{
coutstrtol
(直接在
std::string
上工作的C++11版本:
std::stol
)函数非常适合测试字符串是否包含数字,如果是,数字值是什么

或者你可以继续像以前一样使用iostreams…尝试提取一个数字(
int
double
变量),如果失败,清除错误位并读取字符串。

strtol(直接在
std::string
上工作的C++11版本:
std::stol
)函数非常适合测试字符串是否包含数字,如果包含数字,则测试数字值


或者你可以像以前一样继续使用iostreams…尝试提取一个数字(
int
double
变量),如果失败,请清除错误位并读取一个字符串。

我没有50个rep,因此无法进行评论,这就是为什么我将其作为答案编写。
我认为您可以使用每个字符的Ascii值逐个字符进行检查&如果在两个空格之间有表示数字的Ascii值(在本例中为两个,因为您已将每个单词分隔开),那么您必须将数字除以2。

我没有50个代表,因此无法进行评论,这就是为什么我将其作为答案来写。
我认为您可以使用每个字符的Ascii值逐个字符检查它&如果在两个空格之间有表示数字的Ascii值(在本例中为两个,因为您已经分隔了每个单词),然后您必须将数字除以2。

您可以使用stringstream类来尝试将给定字符串转换为数字。如果尝试成功,您知道 stringstream对象允许您将字符串视为类似于cin或cout的流

将其纳入while循环,如下所示:

while (ss >> word)
{
int value = 0;
stringstream convert(word); //create a _stringstream_ from a string
//if *word* (and therefore *convert*) contains a numeric value,
//it can be read into an _int_
if(convert >> value) { //this will be false if the data in *convert* is not numeric
  cout << value / 2 << endl;
}
else
  cout << word << endl;

}
while(ss>>word)
{
int值=0;
stringstream convert(word);//从字符串创建一个_stringstream
//如果*word*(因此*convert*)包含一个数值,
//它可以读入一个_int_
如果(convert>>value){//如果*convert*中的数据不是数字,则该值为false

cout您可以使用stringstream类(处理字符串和其他数据类型之间的转换)尝试将给定字符串转换为数字。如果尝试成功,您知道 stringstream对象允许您将字符串视为类似于cin或cout的流

将其纳入while循环,如下所示:

while (ss >> word)
{
int value = 0;
stringstream convert(word); //create a _stringstream_ from a string
//if *word* (and therefore *convert*) contains a numeric value,
//it can be read into an _int_
if(convert >> value) { //this will be false if the data in *convert* is not numeric
  cout << value / 2 << endl;
}
else
  cout << word << endl;

}
while(ss>>word)
{
int值=0;
stringstream convert(word);//从字符串创建一个_stringstream
//如果*word*(因此*convert*)包含一个数值,
//它可以读入一个_int_
如果(convert>>value){//如果*convert*中的数据不是数字,则该值为false

非常感谢你,这很有效。我实际上尝试了一些与之几乎相同的东西,只是我没有包括stringstream convert(word);。非常感谢你的帮助。非常感谢,这很有效。我实际上尝试了一些与之几乎相同的东西,只是我没有包括stringstream convert(word)非常感谢你的帮助。