【发布时间】:2014-05-01 05:47:10
【问题描述】:
我在将代码从 c++ 转换为 c 时遇到问题
【问题讨论】:
我在将代码从 c++ 转换为 c 时遇到问题
【问题讨论】:
我们在 C 中使用 FILE 而不是 fstream。
FILE *fp=fopen("test.txt","r+")
if(!fp)
printf("can't open file\n");
while(!feof(fp))
{
i=0;
fscanf(fp,"%lf",&data);
printf("%lf",data);
}
如果你想在 C 中使用 String,你必须使用 Char[]。
char *test = "abcd";
char test2[10] = "abcd";
【讨论】:
在 C 语言中,字符串只能使用 char * 或 char []。
fstream 在 C++ 的基于文件的流上实现高级输入/输出操作。在 C 中,使用 FILE struct 和 fopen/fclose 打开/关闭文件。 fgetc/fputc 读取/写入文件。
【讨论】:
所以对于初学者来说;你可以摆脱 <iostream> 和 <fstream> 包括。将它们替换为<stdio.h>。
如果我没记错的话,你不需要命名空间 std。
用 char* 替换字符串。
将cout 替换为printf。
对于打开/阅读文件,您可以使用fopen。示例:
FILE *ifp, *ofp;
char *mode = "r";
char outputFilename[] = "out.list";
ifp = fopen("in.list", mode);
if (ifp == NULL) {
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
ofp = fopen(outputFilename, "w");
if (ofp == NULL) {
fprintf(stderr, "Can't open output file %s!\n",
outputFilename);
exit(1);
}
更多输入/输出信息请查看here。
【讨论】:
system("pause")。而且没有NULL()。然后查找 ho 以使用 char-arrays 和 scanf