c++文件怎么从文件中读出和写入字符串?

其实我是想问

谁能告诉我怎么编写这个程序:

从文件“file1.txt”中读出一串包含若干数字和英文字母的字符串,将其中的数字字符挑选出来,
并将他们按由小到大的顺序存入文本文件“filenum.txt”中

急求啊,答的快又好的有100分的加分!!!!
说详细点好吗````

一般来说在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文件,一般都使用这种方式操作。 

温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-12-22
FILE *fin=freopen("input.txt","r",stdin);
FILE *fout=freopen("outfile.txt","w",stdout);
加上这个就和普通的命令行下读写一样了。。你可以尝试一下,如果都加上就是文件读写,在控制台就看不到信息的
你可以把input.txt 改成file1.txt然后再处理
第2个回答  2008-12-22
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream input;
input.open("file1.txt");
if (input.fail())
{
cout<<"open the file error!\n";
exit(1);
}

string str;
if (input>>str)//输入串
{
int len = str.length();
string result;
int count = 0;
int i;
for (i = 0; i < len; i++)
{
if (isdigit(str[i]))//判断串里的数字
{
result += str[i];
count++;
}
}

int k;
int temp;

for (i = 0; i < count -1; i++)//排序
{
k = i;
for (int j = i+1; j < count; j++)
{
if (result[j] < result[k])
{
k = j;
}
}

if (k != i)
{
temp = result[k];
result[k] = result[i];
result[i] = temp;
}

}

ofstream output;
output.open("filenum.txt");
if (output.fail())
{
cout<<"open file error!\n";
exit(1);
}

output<<result<<endl;
output.close();
}

input.close();

return 0;

}本回答被提问者采纳
第3个回答  2018-03-22
对任意输入的字符串,将其按照指定的次数插入到指定的文件中
第4个回答  2008-12-22
你打开有误哦! 可可

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网