首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++读文件并处理字符串,该怎么处理

2012-03-14 
c++读文件并处理字符串我从txt文件中要读数据,数据是这样的key123-36-acs -1 0.9key324-55-acs 1 0.7key12

c++读文件并处理字符串
我从txt文件中要读数据,数据是这样的 key123-36-acs -1 0.9
  key324-55-acs 1 0.7
  key123-36-nacs 1 0.8
  。。。。
现在要比较每行的第一个数是否相同,就是比较key123-36-acs,key324-55-acs,key123-36-nacs。。等 

现在key123-36-acs key123-36-nacs就算是相同的,也就是说第二个“—”前相同就算相同
第一个数相同了之后,再比较第三个数,将第三个数最大的那一整行 输出

拜托高手帮忙啦,我的分全送!!!

[解决办法]
void doSomething(const string &itemStr, string &str, float &f)
{
string numStr;

size_t pos = itemStr.find_first_of((" "));
if( pos != string::npos ){
numStr = itemStr.substr(pos+1,itemStr.length());
f = (float)atof( numStr.c_str() );
str = itemStr.substr(0,pos);
}

pos = str.find_last_of(("-"));
if( pos != string::npos )
str = str.substr(0,pos).c_str();
}
例如:
string str = ("key123-36-nacs -10.8"); 
string preString;
float number = 0.0f;
doSomething( str, preString, number );
传入字符串str,获得你需要的第二个“—”前的字符串preString,和第3个数字number
之后的比较就是一个for()。

不太在意效率的情况这样就可以了~

3楼strtok_s()做法存在一个问题。负数-和分隔符-相同。不好拆

[解决办法]
如果只有3个句子的话3个一维字符型数组就行了. 
然后用strcmp()函数,用法自己查

探讨

用一个字符型数组存储这三个字符串,如果只有3个句子的话3个一维字符型数组就行了.
然后用一个for循环从第1个元素开始判断,如果到你要判断停止的位置都相等那么则两者相等.如果不相等,判断ASCII码的大小来判断数的大小.

代码应该很简单.

一个for循环加几条判断语句就行了

[解决办法]
/*
 * main.cpp
 *
 * Created on: 2008-7-22
 * Author: Xuxin_Ran
 */

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
string index, ganymede[3];

ifstream myfile("hello.txt");
if(myfile.is_open()){
int i = 0;
while(!myfile.eof()){
getline(myfile,index);
ganymede[i] = index;
++i;
}
myfile.close();
}
else cout << "file is not open!" << endl;

const char* ot = ganymede[0].c_str();
const char* ot1 = ganymede[1].c_str();
const char* ot2 = ganymede[2].c_str();

int cmp = strcmp(ot,ot1);
if(cmp == 0){
int a;
a = strcmp(ot,ot2);
if(a < 0)
cout << ot2;
else cout << ot;
}
else if(cmp < 0){
int b = strcmp(ot1, ot2);
if(b < 0)
cout << ot2;
else cout << ot1;
}
else {
int c = strcmp(ot, ot2);
if(c < 0)
cout << ot2;
else cout << ot;
}

return 0;
}

热点排行