[英]Reading and Writing to a File using C++
我需要使用fscanf讀取“test.txt”文件中的每一行,並使用fprintf打印到新文件。 如果讀取的行是整數,則將其寫入整數文件。
分別浮動到float文件和字符串到字符串文件。 但是,當我嘗試編譯並運行它時,沒有任何反應,它會進入無限循環。
這是我的代碼
#include <iostream>
#include <stdio.h>
using namespace std;
void writeFloat(){
FILE *file;
FILE *file2;
float value;
file = fopen("test.txt", "r");
file2 = fopen("float.out.txt", "w");
while(!feof(file)){
fscanf(file, "%f", &value);
fprintf(file2,"%f", value);
}
fclose(file);
fclose(file2);
}
void writeInteger(){
FILE *file;
FILE *file2;
int value;
file = fopen("test.txt", "r");
file2 = fopen("int.out.txt", "w");
while(!feof(file)){
fscanf(file, "%d", &value);
fprintf(file2, "%d", value);
}
fclose(file);
fclose(file);
}
void writeString(){
FILE *file;
FILE *file2;
char value;
file = fopen("test.txt", "r");
file2 = fopen("string.out.txt", "w");
while(!feof(file)){
fscanf(file, "%s", &value);
cout<<value<<endl;
fprintf(file2, "%s", value);
}
fclose(file);
fclose(file2);
}
int main(){
writeFloat();
writeInteger();
writeString();
return(0);
}
The test.txt file contains the values:
100
1.6E-10
hey nice to meet you.
43
56
4.5E-09
what is going on?
我不知道我的代碼有什么問題。 請幫我實現我的要求。
feof()永遠不會是真的,因為writefloat()中的fscanf拒絕讀取“嘿”的第一個字母:它不是合法數字的一部分。 然后scanf返回0(“無法讀取任何項目”)。 但是,這還不是EOF。 但是你應該對此做些什么;-)。
此外,在嘗試使用之前,您必須在嘗試閱讀之后檢查eof。 在第一次失敗讀取之前,不會打開eof標志,但不會分配這些變量。
這不是在C ++中打開和關閉文件的常用方法。 它看起來像ac程序。 嘗試使用fstream和iostream庫中的函數。 請參閱http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm 。
我認為,采用不同的策略可能更適合您的需求。
只需要一個函數來逐行讀取文件的內容。 它檢查該行是包含整數還是浮點數。 它行不包含任何數字,該行被寫出“string.out.txt”。 如果數字是整數,則寫出“int.out.txt”。 如果該數字是浮點數,則寫入“float.out.txt”。
使用此策略,您只需讀取輸入文件的內容一次,並僅處理文件的內容一次。
它還簡化了數據的讀取並檢查了何時達到EOF。
#include <stdio.h>
void writeData()
{
FILE *file1 = NULL;
FILE *file2 = NULL;
FILE *file3 = NULL;
FILE *file4 = NULL;
char value;
double realNum = 0.0;
int intNum = 0;
int n = 0;
char line[256];
file1 = fopen("test.txt", "r");
file2 = fopen("string.out.txt", "w");
file3 = fopen("int.out.txt", "w");
file4 = fopen("float.out.txt", "w");
while ( fgets(line, 255, file1) != NULL )
{
// Each line can be plain old text, a floating point number, or an
// integer.
// If the line does not contain a number, assume it is a float.
// Try to read a real number.
n = sscanf(line, "%lf", &realNum);
if ( n == 0 )
{
// The line does not have a number.
// Write the line to the text file.
fputs(line, file2);
}
else
{
// We have a real number.
// Could it be just an integer?
// Read the integer.
sscanf(line, "%d", &intNum);
// How do we decide whether the number is a real number or an
// integer?
// Is 1.0 a real number or an integer?
// Assume for now it is an integer.
if ( realNum == intNum )
{
// We have an integer.
fprintf(file3, "%d\n", intNum);
}
else
{
// We have a real number.
fprintf(file4, "%lG\n", realNum);
}
}
}
fclose(file4);
fclose(file3);
fclose(file2);
fclose(file1);
}
int main()
{
writeData();
return(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.