当前位置: 代码迷 >> C++ >> C++从txt中读取数据,该如何解决
  详细解决方案

C++从txt中读取数据,该如何解决

热度:5431   发布时间:2013-02-26 00:00:00.0
C++从txt中读取数据
本帖最后由 jszjvictor 于 2013-01-28 06:00:06 编辑
请教大家怎么从一个有描述的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++需要读取的只有每行末尾:后的的那个数字

------解决方案--------------------------------------------------------
这里是程序:

#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;
}

------解决方案--------------------------------------------------------
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


------解决方案--------------------------------------------------------
试试这个呢。

#include<iostream>
#include<fstream>
#include<string>
#include <math.h>
using namespace std;

void fn3(string filename);
double StringToInt(string str);
double SignNumberStringToInt(string str);
  相关解决方案