C++从txt中读取数据

jszjvictor 2013-01-28 05:59:13
请教大家怎么从一个有描述的txt中读取数字,而忽略描述,比如:
//total length l: 1
//total time tpmax:1
//time step interval dt: 1.0e-6
//define cell number n: 100
//choice of boundary conditions(1: DIR; 2: ZGD; 3: PER) B: 1
//choice of convection types(1: UDS; 2: CDS; 3: TVD) C: 1
//switch on diffusion?(diffusion: 1; no diffusion: 0) dif: 0
//switch on convection?(convection: 1; no convection: 0) con: 1
就是说C++需要读取的只有每行末尾:后的的那个数字
...全文
874 18 点赞 打赏 收藏 举报
写回复
18 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
赵4老师 2013-02-02
引用 13 楼 jszjvictor 的回复:
引用 11 楼 zhao4zhong1 的回复:C/C++ code?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#include <stdio.h>double l, tpmax, dt;int n, B, C, dif, con; #defin……
是我笔误。 程序员要做的不是尽力避免错误,而是聚焦在快速发现并改正错误。真正以快速方式轻易解决错误,“快速的失败”远胜过“预防错误”。Fred George
  • 打赏
  • 举报
回复
jszjvictor 2013-02-01
引用 3 楼 ppsharp 的回复:
这里是程序: C/C++ code?12345678910111213141516171819202122232425262728293031323334#include <iostream>#include <string>#include <fstream>#include <sstream>using namespace std; int main(void)……
谢谢!
  • 打赏
  • 举报
回复
jszjvictor 2013-02-01
引用 3 楼 ppsharp 的回复:
这里是程序: C/C++ code?12345678910111213141516171819202122232425262728293031323334#include <iostream>#include <string>#include <fstream>#include <sstream>using namespace std; int main(void)……
鞋鞋!
  • 打赏
  • 举报
回复
jszjvictor 2013-02-01
引用 10 楼 nkwanghn 的回复:
试试这个呢。 C/C++ code?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878……
谢谢,现在解决了
  • 打赏
  • 举报
回复
wxx_lq 2013-02-01
MARK! C++ 还是比较方便的
  • 打赏
  • 举报
回复
jszjvictor 2013-01-31
引用 11 楼 zhao4zhong1 的回复:
C/C++ code?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#include <stdio.h>double l, tpmax, dt;int n, B, C, dif, con; #define MAXL 1000char buf[MAXL……
我弄好了,p=strrchr(buf,':'); 谢谢!
  • 打赏
  • 举报
回复
jszjvictor 2013-01-31
引用 11 楼 zhao4zhong1 的回复:
C/C++ code?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#include <stdio.h>double l, tpmax, dt;int n, B, C, dif, con; #define MAXL 1000char buf[MAXL……
非常谢谢您,但是编译的时候 p=strrchr(buf,":"); 无法通过,说 invalid conversion from'const char*'to'char'
  • 打赏
  • 举报
回复
赵4老师 2013-01-30
#include <stdio.h>
double l, tpmax, dt;
int n, B, C, dif, con;

#define MAXL 1000
char buf[MAXL];
FILE *f;
char *p;
int h;
int main() {
    f=fopen("parameter.txt","r");
    if (NULL==f) {
        printf("Can not open file parameter.txt\n");
        return 1;
    }
    h=0;
    while (1) {
        if (NULL==fgets(buf,MAXL,f)) break;
        p=strrchr(buf,":");
        if (p) {
            switch (h) {
                case 0:if (1!=sscanf(p+1,"%lf",&l    )) printf("read l     error!\n"); break;
                case 1:if (1!=sscanf(p+1,"%lf",&tpmax)) printf("read tpmax error!\n"); break;
                case 2:if (1!=sscanf(p+1,"%lf",&dt   )) printf("read dt    error!\n"); break;
                case 3:if (1!=sscanf(p+1,"%d" ,&n    )) printf("read n     error!\n"); break;
                case 4:if (1!=sscanf(p+1,"%d" ,&B    )) printf("read B     error!\n"); break;
                case 5:if (1!=sscanf(p+1,"%d" ,&C    )) printf("read C     error!\n"); break;
                case 6:if (1!=sscanf(p+1,"%d" ,&dif  )) printf("read dif   error!\n"); break;
                case 7:if (1!=sscanf(p+1,"%d" ,&con  )) printf("read con   error!\n"); break;
                default:break;
            }
        } else {
            printf("Error:line %d %s Can not find :\n",h+1,buf);
        }
        h++;
    }
    fclose(f);
    printf("l    =%lf\n",l    );
    printf("tpmax=%lf\n",tpmax);
    printf("dt   =%lf\n",dt   );
    printf("n    =%d\n" ,n    );
    printf("B    =%d\n" ,B    );
    printf("C    =%d\n" ,C    );
    printf("dif  =%d\n" ,dif  );
    printf("con  =%d\n" ,con  );
    return 0;
}
  • 打赏
  • 举报
回复
nkwanghn 2013-01-30
试试这个呢。
#include<iostream>
#include<fstream>
#include<string>
#include <math.h>
using namespace std;

void fn3(string filename);
double StringToInt(string str);
double SignNumberStringToInt(string str);
double SimpleNumberStringToInt(string str);

int _tmain(int argc, _TCHAR* argv[])
{
	fn3("D:\\List.txt");
	system("pause");
	return 0;
}

//function:read data from file
void fn3(string filename)
{
	fstream fs(filename,ios::in||ios::out);
	string string_line;
	string string_number;
	int index;
	double number;
	if(!fs.bad())
	{
		while(getline(fs,string_line))
		{
			cout<<"每行字符串:"<<endl;
			cout<<string_line<<endl;
			index=string_line.find_last_of(':',string_line.size());
			string_number=string_line.substr(index+1);
			string_number.assign(string_number.begin() + string_number.find_first_not_of(' '), string_number.begin() + string_number.find_last_not_of(' ') + 1); 
			cout<<"最后一个冒号后的字符串(去除空格后):"<<endl;
			cout<<string_number<<endl;
			number=StringToInt(string_number);
			cout<<"转换数字为:"<<endl;
			cout<<number<<endl;
			string_number="";
		}		
	}	
}

double StringToInt(string str)
{
	double number;
	int e_index,E_index,cout;
	cout=str.size();
	if(cout==0)
	{
		return -1;
	}
	e_index=str.find_first_of('e');
	E_index=str.find_first_of('E');
	if(e_index!=-1)
	{
		if(E_index!=-1)
		{
			//cout<<"cant convert to number"<<endl;
			return -1;
		}

		if(str.find_first_of('e')!=str.find_last_of('e'))
		{
			//cout<<"cant convert to number"<<endl;
			return -1;
		}
		string str_copy(str);
		string left_str=str.erase(e_index,cout-e_index);
		string right_str=str_copy.erase(0,e_index+1);
		number=SignNumberStringToInt(left_str)*pow(10,SignNumberStringToInt(right_str));
	}
	else
	{
		if(E_index!=-1)
		{
			if(str.find_first_of('E')!=str.find_last_of('E'))
			{
				//cout<<"cant convert to number"<<endl;
				return -1;
			}
			string str_copy(str);
			string left_str=str.erase(E_index,cout-E_index);
			string right_str=str_copy.erase(0,E_index+1);
			number=SignNumberStringToInt(left_str)*pow(10,SignNumberStringToInt(right_str));
		}
		else
		{
			number=SignNumberStringToInt(str);
		}
	}
	return number;
}
double SignNumberStringToInt(string str)
{
	switch(str[0])
	{
		case '+':
			str=str.erase(0,1);
		return SimpleNumberStringToInt(str);
		case '-':
			str=str.erase(0,1);
		return -SimpleNumberStringToInt(str);
		default:
		return SimpleNumberStringToInt(str);
	}
}
double SimpleNumberStringToInt(string str)
{
	int cout=str.size();
	int dot_index;
	double number=0;
	dot_index=str.find_first_of('.');
	if(dot_index==-1)
	{
		for(int i=0;i<cout;i++)
		{
			if(str[i]<48||str[i]>57)
			{
				//cout<<"cant convert to number"<<endl;
				return -1;
			}
			number+=(str[i]-48)*pow(10.0,(double)cout-1.0-i);
		}
		return number;
	}
	else
	{
		for(int i=0;i<dot_index;i++)
		{
			if(str[i]<48||str[i]>57)
			{
				//cout<<"cant convert to number"<<endl;
				return -1;
			}
			number+=(str[i]-48)*pow(10.0,(double)dot_index-1-i);
		}
		for(int i=dot_index+1;i<cout;i++)
		{
			if(str[i]<48||str[i]>57)
			{
				//cout<<"cant convert to number"<<endl;
				return -1;
			}
			number+=(str[i]-48)*pow(10.0,(double)dot_index-i);
		}
		return number;
	}
}
list.txt文件内容 //total length l: 1 //total time tpmax:1 //time step interval dt: 1.0e-6 //define cell number n: 100 //choice of boundary conditions(1: DIR; 2: ZGD; 3: PER) B: 1 //choice of convection types(1: UDS; 2: CDS; 3: TVD) C: 1 //switch on diffusion?(diffusion: 1; no diffusion: 0) dif: 0 //switch on convection?(convection: 1; no convection: 0) con: 1
  • 打赏
  • 举报
回复
jszjvictor 2013-01-29
引用 7 楼 zhao4zhong1 的回复:
C/C++ code?12345678910111213141516#define MAXL 1000char buf[MAXL];FILE *f;char *p;double d;f=fopen...while (1) { if (NULL==fgets(buf,MAXL,f)) break; p=strrchr(buf,":"); if (p) { if (1==s……
不好意思,代码没弄好,是这样的:

double l, tpmax, dt;                                      //define variables
int n, w, B, C, dif, con;                                 //define variables
ifstream inputdata("parameter.txt");                      //open the parameter file
inputdata>>l>>tpmax>>dt>>n>>w>>B>>C>>dif>>con;            //read the parameters to the variables
inputdata.close();                                        //close the parameter file
  • 打赏
  • 举报
回复
jszjvictor 2013-01-29
引用 7 楼 zhao4zhong1 的回复:
C/C++ code?12345678910111213141516#define MAXL 1000char buf[MAXL];FILE *f;char *p;double d;f=fopen...while (1) { if (NULL==fgets(buf,MAXL,f)) break; p=strrchr(buf,":"); if (p) { if (1==s……
谢谢,因为这八个数字读进去是要赋给八个参数的,原来只有数字没有描述的时候,我是这么写的:

double l, tpmax, dt;                                                        //define variables    int n, w, B, C, dif, con;                                                   //define variables    ifstream inputdata("parameter.txt");                                        //open the parameter file    inputdata>>l>>tpmax>>dt>>n>>w>>B>>C>>dif>>con;                              //read the parameters to the variables    inputdata.close();                                                      //close the parameter file
想请教怎么修改上面的代码,只读冒号后面的数字
  • 打赏
  • 举报
回复
sumos 2013-01-28
看看json
  • 打赏
  • 举报
回复
dingqiang107 2013-01-28
strrchr Defined in header <string.h> char *strrchr( const char *str, int ch ); Finds the last occurrence of the character ch in the byte string pointed to by str. Parameters str - pointer to the null-terminated byte string to be analyzed ch - character to search for Return value Pointer to the found character in str, or NULL if no such character is found. Example #include <string.h> #include <stdio.h> int main() { char szSomeFileName[] = "foo/bar/foobar.txt"; char *pLastSlash = strrchr(szSomeFileName, '/'); char *pszBaseName = pLastSlash ? pLastSlash + 1 : szSomeFileName; printf("Base Name: %s", pszBaseName); } Output: Base Name: foobar.txt
  • 打赏
  • 举报
回复
ppsharp 2013-01-28
这里是程序:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main(void)
{
	const char filename[] = "test.txt";
	ifstream fs;
	string line;
	string temp;
	int n = 0;
	int num = 0;
	stringstream ss;

	fs.open(filename);
	if(!fs.is_open())
	{
		cout<<"不能打开文件"<<filename<<endl;
		return 1;
	}
	
	while (getline(fs, line))
	{
		ss.str(line);
		n = line.rfind(':');
		temp = line.substr(n+1);
		cout<<temp<<endl;
	}

	getchar();
	return 0;
}
  • 打赏
  • 举报
回复
spaceman10 2013-01-28
find_last_of(";")和substr();
  • 打赏
  • 举报
回复
逐行读取,然后构造字符串,查找最后出现的字符“:” “:”后面的就是数字了。
  • 打赏
  • 举报
回复
赵4老师 2013-01-28
#define MAXL 1000
char buf[MAXL];
FILE *f;
char *p;
double d;
f=fopen...
while (1) {
 if (NULL==fgets(buf,MAXL,f)) break;
 p=strrchr(buf,":");
 if (p) {
  if (1==sscanf(p+1,"%lf",&d)) {
   printf("%lg\n",d);
  }
 }
}
fclose(f);
  • 打赏
  • 举报
回复
Darkingp 2013-01-28
每读取一行,就对该行字符串进行操作,string类型有一个find函数,找到‘:'然后直接得到':'后面的字符串,需要使用数字的话可以再用atoi函数转为数字
  • 打赏
  • 举报
回复
相关推荐
发帖
C++ 语言
加入

6.0w+

社区成员

C++ 语言相关问题讨论,技术干货分享,前沿动态等
申请成为版主
帖子事件
创建了帖子
2013-01-28 05:59
社区公告
暂无公告