将C ++字符串转换为int [英] Converting c++ string to int

查看:214
本文介绍了将C ++字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++字符串中有以下数据

I have the following data in a c++ string

John Doe 01.01.1970

我需要从中提取日期和时间到int变量中。我是这样尝试的:

I need to extract the date and time from it into int variables. I tried it like this:

int last_space = text_string.find_last_of(' ');
int day = int(text_string.substr(last_space + 1, 2));

但是我从类型'std :: basic_string'输入的无效类型转换'int'。当我在另一个字符串变量中提取 John Doe部分时,一切正常。怎么了?

But I got invalid cast from type ‘std::basic_string’ to type ‘int’. When I extract the "John Doe" part in another string variable, all works fine. What's wrong?

我正在尝试使用g ++ -Wall -Werror进行编译。

I am trying to compile it with g++ -Wall -Werror.

推荐答案

使用流来解码字符串中的整数:

Use streams to decode integers from a string:

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

int main()
{
    std::string         x = "John Doe 02.01.1970";

    std::string         fname;
    std::string         lname;
    int                 day;
    int                 month;
    int                 year;
    char                sep;

    std::stringstream   data(x);
    data >> fname >> lname >> day >> sep >> month >> sep >> year;

    std::cout << "Day(" << day << ") Month(" << month << ") Year(" << year << ")\n";
}

与字符串变量一起使用的运算符>>将读取单个(白色)空格分开的单词。与整数变量一起使用时,将从流中读取一个整数(丢弃任何进行中的(空白)空间。)

The operator >> when used with a string variable will read a single (white) space separate word. When used with an integer variable will read an integer from the stream (discarding any proceeding (white) space).

这篇关于将C ++字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆