c++读取文件中的字符串

.txt格式文件内容如下:
1.847133 10.3.1.112 192.168.1.95 HTTP
963
1.953884 192.168.1.95 10.3.1.112 HTTP
250
8.166636 10.3.1.112 192.168.1.95 HTTP
885
9.770307 192.168.1.95 10.3.1.112 HTTP
60
9.773000 10.3.1.112 192.168.1.95 HTTP
809
9.775774 10.3.1.112 192.168.1.95 HTTP
890
9.781554 192.168.1.95 10.3.1.112 HTTP
767
9.899587 192.168.1.95 10.3.1.112 HTTP
320
9.917631 10.3.1.112 192.168.1.95 HTTP
826
10.142553 192.168.1.95 10.3.1.112 HTTP
292
想以两行为一组,以字符串的格式读入到二维数组中。
以前两行为例,a[0][0]=1.847133 a[0][1]=10.3.1.112 a[0][2]=192.168.1.95 a[0][3]=HTTP
a[0][4]=963
a[1][0]=…………
如何实现
问下vc++里有string类型的数组吗。
ifstream ifs("2.txt"); // 改成你要打开的文件
streambuf* old_buffer = cin.rdbuf(ifs.rdbuf());

string read,*a[5][5];
while(cin >> read) // 逐词读取方法一
{
cout << read;
printf("\n");
}
cin.rdbuf(old_buffer); // 修复buffer
找的算法能从文件逐个数据的读出来,显示出来。但我不知道怎么存放至数组当中,还有数组该怎么定义?
是定义成char *a[][]这种格式吗?

c++读取文件中的字符串的代码如下:

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
 ifstream ifs("zhidao.cpp"); // æ”¹æˆè¦è¯»å–字符串的那个的文件
 char buffer[256];
 while(ifs.getline(buffer, 256, ' ')) // é€è¯è¯»å–
 {
  cout << buffer;
 }
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-08-14
你的string read,*a[5][5];
最好定义成string read;
char *a[5][5];
程序:
int x = 0,y = 0;
while(cin >> read) // 逐词读取方法一
{
cout << read;
a[x][y] = new char(100);
strcpy(a[x][y], read.c_str());
y++;
if (y > 4) {
y = 0;
x++;
}

if (x > 4) {
break;
}
}
这样应该就行了。本回答被提问者采纳
第2个回答  2009-08-14
ifstream in;
in.open("文件名.txt");
int count=0;
while(in)
{
in>>a[count][0];
in>>a[count][1];
in>>a[count][2];
in>>a[count][3];//如果一行后面有空格,可以加上一句:getline(in,tmpString);
getline(in,a[count][4]);
count++;
}
in.close();

你学过C++吧,建议你从基础学起。
相似回答