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()函数,用法自己查
[解决办法]
/*
* 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;
}