简体   繁体   English

检查字符串是否为数字,然后将该数字转换为整数?

[英]Checking if a string is a number, then converting that number to an int?

The 'program' is to take input in then spit the string back out on seperate lines and all numbers are to be multiplied by two in this case. “程序”将接受输入,然后在单独的行上将字符串吐回去,在这种情况下,所有数字都应乘以2。

My issue occurs when a number is input after a white space. 在空格后输入数字时会发生我的问题。 Example

Sentence: 12 fish

Outputs: 输出:

24     
fish

But... 但...

Sentence: there are 12

Outputs: 输出:

there
are
0

The program I have written: 我写的程序:

#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;

int main()
{
    string str;
    int number = 811;
    cout << "Sentence: ";
    getline(cin,str);

    istringstream iss(str);

     while(iss)
     {
            bool ree = 0;
            string word;
            iss >> word;

            if(isdigit(word[0]))
            {
                stringstream(str) >> number;
                number = (number * 2);
                cout << number << endl;
                ree = 1;
                number = 911;
            }

           if(!ree)
           {
            cout << word << endl;
           }

           ree = 0;

      }
}

Hopefully it's something small I am not seeing! 希望这是我看不到的小东西! Thanks for the help in advanced. 感谢您的帮助。

The problem is that 问题是

stringstream(str) >> number;

creates a fresh string stream from the initial sentence, then tries to extract from it into number . 从初始句子创建一个新的字符串流,然后尝试将其提取为number Of course that will fail (as the first word in the sentence is not a number). 当然这会失败(因为句子中的第一个单词不是数字)。 If you wonder why number was set to 0, that's because on failure, the stringstream::operator>> zeros the argument (since C++11). 如果您想知道为什么将number设置为0,那是因为失败时, stringstream::operator>>会将参数清零(自C ++ 11起)。

" If extraction fails, zero is written to value and failbit is set. " ... 如果提取失败,则将零写入值并设置故障位。 ” ...

Before C++11, it left the argument unchanged. 在C ++ 11之前,它保持不变。 See the documentation for more details. 有关更多详细信息,请参见文档

The correct way is to use a conversion from string to int (or long ), namely std::stoi , and replace that line by 正确的方法是使用从字符串到int (或long )的转换,即std::stoi ,并将该行替换为

try{
    number = std::stoi(word); 
}
catch(std::exception& e){
    std::cout << "error converting" << '\n';
}

使用stoi解析输入,如下所示:

int num = std::stoi(input);

using stoi is easy, and you can lazily catch the exception by the following: 使用stoi很容易,您可以通过以下方式懒惰地捕获异常:

if(!stoi(string)){
    std::cout << "caught a non integer string" << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM