![]() |
#2
Jonny02012018-07-13 12:16
要么都用 C++
要么都不用 文件读写 C++ 有 fstream, 不需要用 C 的函数, 并且用 C 的函数要使用 C++ 标准库提供的与 C 交互的部分 scanf 我记得没有 %s, C 语言里对字符串的读写我记得使用 get 和 put string 不能直接传给 C 的函数, C 里面接受的基本都是 const char *, string 有提供与 C 风格字符串交互的函数 : string::c_str() 你这样的程序我建议干脆不要用 C++, 名字的输入直接用 char *, 这样就可以直接传进去了 我根据编译错误随便改了一下, 还有一个警告我就不管了, 程序逻辑是否有错误自己纠正 ![]() #include<iostream> #include<stdio.h> #include<string> using namespace std; //string filename; int file(); int file2(); int main(){ std::string choise; while(1){ std::cout<<"write file or read file?"<<std::endl; cin >> choise; if(choise=="write "){ file(); } else file2(); } return 0; } int file(){ FILE *fp; std::string filename; int i; std::cout<<"enter the filename you want to write\n"; //for(i=0;i<8;i++) cin >> filename; fp=fopen(filename.c_str(),"w");//error std::cout<<"enter the string that you want to write into the file\n"; std::string writefile; cin >> writefile; fprintf(fp,"%s\n",writefile.c_str()); printf("finish write file,file will close and back to main()\n"); fclose(fp); return 0; //main(); } int file2(){ FILE *fp; std::string filename; std::string files; cin >> filename; fp=fopen(filename.c_str(),"r");//error printf("in %s ,things in the file is\n",filename.c_str()); fscanf(fp,"%s",files.c_str()); printf("%s\n",files.c_str()); fclose(fp); printf("finish read file,file will close and back to main()\n"); return 0; } |
出了点错误(该程序有C语言成分)
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
//string filename;
int file();
int file2();
int main(){
std::string choise;
while(1){
std::cout<<"write file or read file?"<<std::endl;
scanf("%s",&choise);
if(choise=="write "){
file();
}
else
file2();
}
return 0;
}
int file(){
FILE *fp;
std::string filename;
int i;
std::cout<<"enter the filename you want to write\n";
//for(i=0;i<8;i++)
scanf("%s",&filename);
fp=fopen(filename,"w");//error
std::cout<<"enter the string that you want to write into the file\n";
std::string writefile;
scanf("%s",&writefile);
fprintf(fp,"%s\n",writefile);
printf("finish write file,file will close and back to main()\n");
fclose(fp);
return 0;
//main();
}
int file2(){
FILE *fp;
std::string filename;
std::string files;
scanf("%s",&filename);
fp=fopen(filename,"r");//error
printf("in %s ,things in the file is\n",filename);
fscanf(fp,"%s",&files);
printf("%s\n",files);
fclose(fp);
printf("finish read file,file will close and back to main()\n");
return 0;
}