c++问题

  • 主题发起人 主题发起人 T-Mac
  • 开始时间 开始时间

T-Mac

新手上路
注册
2006-07-15
消息
113
荣誉分数
2
声望点数
28
我有个C++的问题在linux底下。
我需要读文件(文件其实是matrix)比如:
1 2 1
3 2 1
3 1 2

P1)我已经把每行弄成string了。用atoi()不太好使。大家有什么建议或连接可以参考。

P2)c++里std exception里能handle non-existing file exception?每次我开一个non-existing file它都试着建一个,这个问题不是太重要不过想知道下。
在c 里可以用 ios::nocreate flag 阻止。不知道c++怎么办。自己写function handle?

谢谢任何建议。
 
希望对你有用
代码:
void LoadHenna()
{
	FILE *stream;
	int i;
	LPHENNA aHenna;
	stream = fopen( "henna.txt", "r" );
	
	aHenna = (LPHENNA)GlobalAlloc(GMEM_ZEROINIT, sizeof(HENNA));
	HennaTable.push_back(aHenna);

	i = 0;
	while (!feof(stream))
	{
		aHenna = (LPHENNA)GlobalAlloc(GMEM_ZEROINIT, sizeof(HENNA));
		fscanf(stream, 
			"henna_begin\t%d\tdye_id=%d\tdye_amount=%d\trefund=%d\tdraw_price=%d\tremove_price=%d\tint=%d\tstr=%d\tcon=%d\tmen=%d\tdex=%d\twit=%d\thenna_end\n",
						&(aHenna->symbol_id),
						&(aHenna->dye_id),
						&(aHenna->dye_amount),
						&(aHenna->refund),
						&(aHenna->drawprice),
						&(aHenna->removeprice),
						&(aHenna->inn),
						&(aHenna->str),
						&(aHenna->con),
						&(aHenna->mem),
						&(aHenna->dex),
						&(aHenna->wit));
		if (aHenna->symbol_id == 0)
		{
			Print(0x18AA81D8, 2, L"Parser HennaTable ERR :[%d]", i);
			GlobalFree(aHenna);
			break;
		}
		HennaTable.push_back(aHenna);
		i++;
	}
	fclose( stream );
	stream = NULL;
	Print(0x18AA81D8, 0, L"g_HennaTable Created ... [%d] Hennas", HennaTable.size() - 1);
}
代码:
			pch = strpbrk(buffer, ";");
			if (pch != NULL)
			{
				while (pch != NULL)
				{
					itemCount++;
					pch = strpbrk (pch+1,";");
				}
				//Print2(0x18AA81D8, 2, "[%d]", itemCount);
				pch = buffer + 1;
				for (int j=0;j<itemCount;j++)
				{
					sscanf(pch, "%d", &hennaid);
					aHennaTree->symbolids->push_back(hennaid);
					aHennaTree->dyeids->push_back(HennaTable.at(hennaid)->dye_id);
					pch = strstr (pch,";") + 1;
				}
			}
 
i did not try strpbrk but i tried strtok(sentence, " \n");
doesnot look nice . i will think about your code. thanks for your help.
 
已经搞定。费了半天劲用stringstream就行了,然后一转成int,唉~~~。不过还是谢谢热狗同学。^_*

不过谁能解释下第2个问题?
 
用ifstream,只读不写的流.

用ifstream,只读不写的流.
 
如果是linux,可以试试QT。
这些东西QString, QStringList, QFile可能一句话就能办到。
 
I have code to handle your first problem. I will post it on Monday.
P2: do you use C++ or C code to open a file? If your code does not use Qt, you'd better not use Qt since you need to install it. For commercial use, you need to buy license.
 
The following code is better than atoi() because atoi() does not work well if input string is not int.

bool string2Int( const char * const value_str, int & value )
{
if ( value_str == 0 )
{
return false;
}

char othercrap = '.';
if ( sscanf( value_str, "%d %c", &value, &othercrap ) == 1 )
{
return true;
}

return false;
}
 
后退
顶部