字符串转换为其他类型

之前曾经为字符串转化为整数而苦恼,每次都是用atoi这个函数,并且用strtok_s函数进行字符串的分割。
之前参加过华为软件精英挑战赛的时候,读取文件流中的数据是这样写的,现在看来发现里面有很多问题,代码如下:
首先看下文件格式:
在这里插入图片描述

void Astar::readMap(string file,int **arr,int col)
{
	int row=-1,colTemp = 0;
	string temp="";
	char a[100] ="";
	char *midTemp =new char[100];
	char *p;

	ifstream inFile;
	inFile.open(file,ios::in);
	if (!inFile.is_open())
		cout << "open file failure" << endl;
	//复位光标
	//inFile.clear();
	//inFile.seekg(0,inFile.beg);

	while (getline(inFile,temp))
	{
		row++;
		if (row == 0) continue;
		for (int j=0;j<temp.length();j++)
		{
			a[j] = temp[j];
		}
		
		midTemp=strtok_s(a, " (),",&p);
		while ((midTemp!=NULL)&&(colTemp<col))
		{
			arr[row - 1][colTemp] = atoi(midTemp);
			midTemp = strtok_s(NULL, "(),",&p);
			colTemp++;
		}
		temp = ""; colTemp = 0;
	}
	inFile.close();
	return;
}

如今发现一个更好的函数进行字符串转换,此处只是介绍该函数的用法,并不对上述代码进行修改。

#include<iostream>
#include<sstream>

using namespace std;

class Solution
{
public:
	int a;
	float b;
	void stringToInteger(const string s)
	{
		stringstream str;
		str << s;//会一次性把s输入到str
		str >> a;//每次输出遇到空格或者换行符就停止

		str >> b;
	}
};

int main()
{
	string s = "123123 \n321.2";
	Solution solution;
	solution.stringToInteger(s);//输入的数据不能超过所定义数据类型的最大值,不然会出错
	cout << s << endl;
	cout << solution.a << " " << solution.b << endl;
	system("pause");
	return 0;
}

输出结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37708045/article/details/89310196