1. 程式人生 > >c++學習(1): string資料型別及stringstream進行資料型別的轉換

c++學習(1): string資料型別及stringstream進行資料型別的轉換

1、在c++中string可以直接定義一個字串如:string s;而在c中字串只能用char定義,存放在char陣列當中如:char s[100];

2、在c++中讀取一行:getline(cin, s);在c中讀取一行gets(s);

3、在c++中字串長s.length()或s.size();在c中strlen(s);

4、在c++中字串的比較s=="hello";在c中strcmp(s, "hello");

5、stringstream作用在於安全的進行資料的型別轉換

以下面的應用為例:

#include "ros/ros.h"
#include "std_msgs/String.h"

#include <sstream>   //stringstream標頭檔案

int amin(int argc, char **argv)
{
    ros::init(argc, argv, "talker");  //初始化節點

    ros::NodeHandle n;
    ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); //釋出string型別的訊息

    ros::Rate loop_rate(10);  //10hz 即每秒十次
    int count = 0;
    while (ros::ok())   //只有1、“ctrl+c”才能停止 2、呼叫shoutdown();......
    {
        std_msgs::String msg;  //定義一個string型別訊息
        std::stringstream ss;  //定義一個stringstream型別資料流
        ss << "hello world" << count;  //將count與"hello world"相加, 輸入到ss中
        msg.data = ss.str();  //將ss中的訊息轉化為型別 並賦給msg

        ROS_INFO("%s", msg.data);
        chatter_pub.publisher(msg);  //釋出msg訊息

        ros::spinOnce();

        loop_rate.sleep();

        ++count;
    }

    return 0;
}