strtok_s use


来源 :http://www.cplusplus.com/forum/general/13058/


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

using namespace std;

// Example file contents:
// -ie; Simple individual lines of 3-doubles representing
//   each point's x, y, and z coordinates.
// -BUT...somebody added commas into the data file!
//
//	1.01, 2.02, 3.03
//	4.04, 5.05, 6.06
//	7.07, 8.08, 9.09
//
// etc...
//

const string points_filename("data.txt");

string CleanLine(const string& n)
{
	string cleanline;
	char* char_line = (char*)n.c_str();

	char* token = NULL;
	char* context = NULL;
	char delims[] = ",\t\n";

	token = strtok_s(char_line,delims,&context);

	while(token != NULL)
	{
		cleanline += token;
		cleanline += ' ';
		token = strtok_s(NULL, delims, &context);
	}

	return cleanline;
}

int main(void)
{
	ifstream in_fs(points_filename.c_str());
	if ( ! in_fs) cerr << "no points file\n";

	string line, cleanline;
	stringstream ss;

	double x, y, z;
	long point_count = 0;

	// Read through all the file lines, extract and display the cleaned data.
	//
	while (getline(in_fs, line)) 
	{

		// Clean each line.
		cleanline = CleanLine(line);

		// Pass the cleaned-up string into a stringstream, to parse out the data elements.
		ss << cleanline;

		// Stringstream will parse directly on whitespace.
		ss >> x >> y >> z;					// TODO: Type compatibility checking.

		// Test display of output.
		cout << "For point number: " << point_count
			  << "\t x: " << x 
			  << "\t y: " << y 
			  << "\t z: " << z << endl;

		++point_count;
	}

	cin.get();
	cin.get();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值