임의의 배열을 생성하려고합니다.파일이 올바르게 설정되었지만 예기치 않게 새 스트림에서 eof() 및 peek()이 잘못된 값을 반환합니다.
void Random_nums(int n, string fileName) {
ofstream fsave(fileName);
int ranArray[n];
srand((unsigned int)time(NULL));
for(int i=0; i<n; i++)
{
ranArray[i]=rand()%2001 - 1000;
fsave << ranArray[i] << '\n'; //save them into ranArray
}
fsave.close();
}
그리고 개별 파일에 저장하고 싶습니다.
그런 다음 방금 저장 한 데이터를 읽고 새로운 기능으로 구현하고 싶습니다.
void FunctionWantToUse(string inputFile, string outputFile) {
//reading data
ifstream fin(inputFile);
cout << fin.is_open();//which is 1
//how many numbers are there in this file
int n = 0;
n = distance(istream_iterator<int>(fin), istream_iterator<int>());
//restore the array
int array[n];
//test
cout << fin.peek() << ' ' << EOF;//they are both -1!
//another test
cout << fin.peek() << '\n'; //which return -1
cout << fin.eof() << '\n'; //which return 1
//since peek() and EOF both return -1, I can't get into this loop.
while (fin.peek() != EOF) {
if ((fin >> array[i]).good()) {
cout << array[i];
}
}
은 완전히 왜 -1 fin.peek()와 fin.eof() 변화의 값 1은 각각 모른다.
그리고이 두 기능을 실행하면 콘솔에서이 사실을 알려줍니다. I는 난수를 생성 할 때
-1 -1-1
1
Process finished with exit code 0
I은 또한 루프의 장소 fsave.eof()와 같은 다른 검사를 제공하고, 그것은 모두 0을 출력한다.
누군가가 여기에 무슨 일이 일어나는지 말해 줄 수 있습니까? 나는 지금 전혀 실마리가 없다.
'istream :: eof()'는'bool'을 반환합니다. 'bool' 만 출력하면'0' 또는'1' 값을 갖습니다. 'EOF'는 일반적으로'int' 리터럴로 확장되는 C의 매크로로 보통 문자의 범위를 벗어나는 값을 가지므로 '0'이나 '1'이 될 수 없습니다. 그러므로'EOF'와'fin.eof()'는 같은 것을 비교할 수 없다. 간단한 해결책 : C 매크로 (예 :'EOF')를 사용하여 C++ 스트림의 상태를 테스트하지 말것. – Peter