C++如何从文件中读取字符串

文件中一行有两个字符串,两个字符串中间用若干个空格分开,怎么将两个字符串分别读到两个字符数组中

一般来说在C++语言中读取txt文件的信息有三种方法:

1、使用C语言标准文件I/O中的fopen()、fread()等等函数。示例如下(vc6.0下编译通过):

#include<stdio.h>
FILE*stream;
void main(void)
{
long l;
float fp;
char s[81];
char c;
  
stream=fopen("fscanf.out","w+");
if(stream==NULL)
printf("Thefilefscanf.outwasnotopened\n");
else
{
fprintf(stream,"%s%ld%f%c","hello world",  
65000,3.14159,'x');
/*Setpointertobeginningoffile:*/
fseek(stream,0L,SEEK_SET);
/*Readdatabackfromfile:*/
fscanf(stream,"%s",s);
fscanf(stream,"%ld",&l);
fscanf(stream,"%f",&fp);
fscanf(stream,"%c",&c);
/*Outputdataread:*/
printf("%s\n",s);
printf("%ld\n",l);
printf("%f\n",fp);
printf("%c\n",c);
fclose(stream);
}
}

2、使用C++语言中的文件I/O中的ofstream,ifstream,fstream。示例如下(vc6.0下编译通过):

 #include <iostream>
    #include <fstream>
    #include <cstdlib>
      using namespace std;
     
    int main () {
        char buffer[256];
        ifstream in("test.txt");
        if (! in.is_open())
        { cout << "Error opening file"; exit (1); }
        while (!in.eof() )
        {
            in.getline (buffer,100);
            cout << buffer << endl;
        }
        return 0;
    }

3、使用操作系统中的API函数,比如Windows上的ReadFile()、OpenFile()等等,现在操作系统一般都具备内存文件映射功能,对于大的txt文件,一般都使用这种方式操作。

温馨提示:答案为网友推荐,仅供参考
相似回答