积极答复者
C++的ifstream流读取txt文件定位下一行的问题

问题
答案
-
Hi pucx,
您可以把之前的while循环语句改成如下:
while(!ifs.eof()&&!ifs.fail())
{
getline(ifs, str);
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, str.c_str());
int count=1;
int i=0;
int j[300];
int k=0;
for(i=0;i<29;i++)
{
if(nstring[i]==' ')
{
count++;
j[k]=i;//把空格的位置存在j数组里
k++;
}
}
for(count=48;count<=178;count++) //读取每行数据的第50个到第180个数据
{
for( i=j[count]+1;i<j[count+1];i++)//输出两个空格之间的值
{
cout<<nstring[i];
}
cout<<" ";
}
cout<<endl;
}
我们这里只能提供一个思路,您可以根据这个思路,按照自己的需求写相应的代码。
>>那可不可以用C的File文件方法实现呢?、
可以C的File文件方法实现.
File I/O Functions :http://msdn.microsoft.com/en-us/library/aa916914.aspx
请把有用的回答标记为答案。
谢谢,
Lucy
Lucy Liu [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 lucy-liuModerator 2010年12月31日 7:55
全部回复
-
Hi pucx,
我们可以通过getline获取每行的数据放到string类型的字符串中。
再把string类型转成char *类型。
最后,通过一个循环语句就可以读取字符数组指定位置指定大小的数据了。
以下是具体步骤:
1.创建一个win32 的控制台程序;
2.输入以下代码:
#include "stdafx.h" #include <fstream> #include <iostream> #include <string> #include <sstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { ifstream ifs("C:\\Users\\v-lucli\\Desktop\\hs.txt"); if(!ifs) { cout<<"can not open file"; return -1; } string str; while(!ifs.eof()&&!ifs.fail()) { getline(ifs, str); const size_t newsize = 100; char nstring[newsize]; strcpy_s(nstring, str.c_str()); for(int i=2;i<5;i++) { cout<<nstring[i]; } cout<<endl; } return 0; }
谢谢,
Luxy
Lucy Liu [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
Hi Lucy-Liu
你的程序如果说数据是
23456
563246
4567892
34564
567890
这样的数据的话还行,但是如果说数据是以下的情况呢?
2 3 4 5 6
5 6 3 2 4 6
4 5 6 7 8 9 2
3 4 5 6 4
5 6 7 8 9 0
...
还有这样的数据文件情况呢?
2 333 4 54 6
5 6 311 2 4 6
4 5 62 7 8334 9 2
3 42 5 6 422
52 6 7 8 922 20
...
这样的情况就不行的啊?我需要的是能够读取后面两种情况的。
还请指教。谢谢! -
Hi pucx,
您可以把之前的while循环语句改成如下:
while(!ifs.eof()&&!ifs.fail())
{
getline(ifs, str);
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, str.c_str());
int count=1;
int i=0;
int j[300];
int k=0;
for(i=0;i<29;i++)
{
if(nstring[i]==' ')
{
count++;
j[k]=i;//把空格的位置存在j数组里
k++;
}
}
for(count=48;count<=178;count++) //读取每行数据的第50个到第180个数据
{
for( i=j[count]+1;i<j[count+1];i++)//输出两个空格之间的值
{
cout<<nstring[i];
}
cout<<" ";
}
cout<<endl;
}
我们这里只能提供一个思路,您可以根据这个思路,按照自己的需求写相应的代码。
>>那可不可以用C的File文件方法实现呢?、
可以C的File文件方法实现.
File I/O Functions :http://msdn.microsoft.com/en-us/library/aa916914.aspx
请把有用的回答标记为答案。
谢谢,
Lucy
Lucy Liu [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 lucy-liuModerator 2010年12月31日 7:55