28 / 28 / 7
Регистрация: 03.10.2009
Сообщений: 122
1

форматированный ввод из файла, fscanf не считывает значения из файла: возвращает 0,

09.05.2011, 14:21. Показов 2309. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Для ввода использую библиотеку <stdio.h>, в функции, представленной дальше, файл в одном компиляторе открывается, в другом даже не открывается, но главное, что меня интересует - почему fscanf не читает из потока: возвращает значение 0 (количество прочитанных значений);
аналогичная ситуация была при работе с библиотеками <fstream.h>, <iomanip.h>;
подскажите, что я упустил из виду, пожалуйста.
функция, в которой возникают вопросы:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
double t(double x)throw(char*)
{       FILE *fp;
        char* fn;
        if (fabs(x) <= 1)
                fn = ("dat_X1.dat");
        if (x < -1)
                {
                x = 1/x;
                fn = ("dat_X3.dat");
                }
        if (x > 1)
                {
                x = 1/x;
                fn = ("dat_X2.dat");
                }
        fp = fopen(fn, "r");
        if (fp == NULL)
                throw "File can't be opened!\n";
        float temp;
        while ((fscanf(fp,"%f",&temp) != EOF))           //           здесь !
                {
                if (temp == x)
                        break;
                fscanf(fp,"%f",&temp);
                fscanf(fp,"%f",&temp);
                }
        if (temp == x)
                {
                fscanf(fp,"%f",&temp);
                fclose(fp);
                return temp;
                }
        else    {
                fclose(fp);
                temp = tt(x,fn);
                return temp;
                }
}
есть еще 3 аналогичные, там, наверное, будет то же;
Весь код программы:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <math.h>
 
#include <iostream.h>
#include <conio.h>
 
#include <stdio.h>
#include <stdlib.h>
 
//---------------------------------------------------------------------------
 
 
double fun(double x, double y, double z);
 
double grs1(double x, double y, double z);
double grs2(double x, double y, double z);
double grs3(double x, double y, double z);
 
double rrz1(double x, double y, double z);
double rrz2(double x, double y, double z);
double rrz3(double x, double y, double z);
 
double qrz1(double x, double y);
double qrz2(double x, double y);
double qrz3(double x, double y);
 
double srs1(double x, double y, double z)throw(int);
double srs2(double x, double y, double z);
double srs3(double x, double y, double z);
 
double srz(double x, double y, double z);
 
double t(double x)throw (char*);
double tt(double x, char*)throw (char*);
double u(double x)throw (char*);
double uu(double x, char*)throw (char*);
 
//--------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{       double x,y,z;
        cout<<"Type x, y, z!\n";
        cout<<"x =\t";
        cin>>x;
        cout<<"y =\t";
        cin>>y;
        cout<<"z =\t";
        cin>>z;
 
        double result = fun(x,y,z);
        cout<<result;
        getch();
 
        return 0;
}
//---------------------------------------------------------------------------
double fun(double x, double y, double z)
{       double result;
        try
        {
        try
                {
                result = (x*grs1(x,y,z)+y*grs1(x,z,y));
                }
        catch (int algoritm)
                {
                cout<<"This is int catch!\n";
                switch (algoritm)
                        {
                         case 2:
                         {
                         result = (x*grs2(x,y,z)+y*grs2(x,z,y));
                         break;
                         }
                         case 3:
                         result = (x*grs3(x,y,z)+y*grs3(x,z,y));
                        }
                }
        }
        catch (char* ex)
                {
                cout<<"This is  char catch!\n";
                cout<<ex;
                result = 1.3489 * x + 2.2362 * y  * z -2.348 * x * y;
                }
        return result;
 
}
double grs1(double x, double y, double z)
{
        return  (0.3189 * rrz1(x,y,y) + 1.8389*rrz1(x-y,z,y));
}
double grs2(double x, double y, double z)
{
        return  (0.3189 * rrz2(x,y,y) + 1.8389*rrz2(x-y,z,y));
}
double grs3(double x, double y, double z)
{
        return  (0.3189 * rrz3(x,y,y) + 1.8389*rrz3(x-y,z,y));
}
double rrz1(double x, double y, double z)
{
        return (x>y)?   (x*z*qrz1(y,z)) : (y*x*qrz1(x,y));
}
double qrz1(double x, double y)
{
        return (fabs(x)<1)?     (x*srs1(x,y,x)) : (y*srs2(y,x,y));
}
double srs1(double x, double y, double z)throw(int)
{
        if ( (z>y) && (z*z+x*y > 0) )
                return (srz(x,y,z) + y*sqrt(z*z+x*y)) ;
 
        if ( (x*x + z*y > 0)&&(z<=y) )
                return (y+srz(z,x,y) * sqrt(x*x + z*y));
 
        if (z*z + x*y <= 0)
                throw 2;
 
        if (x*x + z*y <= 0)
                throw 3;
}
double srz (double x, double y, double z)
{
        return (x>y)?   (t(x)+u(z)-t(y)) : (t(y)+u(y)-u(z));
}
double t(double x)throw(char*)
{       FILE *fp;
        char* fn;
        if (fabs(x) <= 1)
                fn = ("dat_X1.dat");
        if (x < -1)
                {
                x = 1/x;
                fn = ("dat_X3.dat");
                }
        if (x > 1)
                {
                x = 1/x;
                fn = ("dat_X2.dat");
                }
        fp = fopen(fn, "r");
        if (fp == NULL)
                throw "File can't be opened!\n";
        float temp;
        while ((fscanf(fp,"%f",&temp) != EOF))
                {
                if (temp == x)
                        break;
                fscanf(fp,"%f",&temp);
                fscanf(fp,"%f",&temp);
                }
        if (temp == x)
                {
                fscanf(fp,"%f",&temp);
                fclose(fp);
                return temp;
                }
        else    {
                fclose(fp);
                temp = tt(x,fn);
                return temp;
                }
}
double tt(double x, char* fn)throw (char*)
{
        FILE *fp;
        if ( (fp=fopen(fn,"r")) == NULL)
                throw "File can't be opened!\n";
 
        double tempC, tempN; //current, next
        fscanf(fp,"%f",&tempN);
        tempC = tempN;
        fscanf(fp,"%f",&tempN);
        fscanf(fp,"%f",&tempN);
        while ( (fscanf(fp,"%f",&tempN)!=EOF) )
                {
                if ( (x > tempC) && (x<tempN) )
                        break;
                tempC = tempN;
                fscanf(fp,"%f",&tempN);
                fscanf(fp,"%f",&tempN);
                }
        if ( (x > tempC) && (x<tempN) )
                {
                fclose(fp); 
                return  ( t(tempC) +  (x - tempC)/(tempN-tempC) );
                }  
        else
                {cout<<"Error: Wrong x (func. tt)\n";
                 getch();
                 exit(1);}
}
 
double u(double x)throw(char*)
{       FILE *fp;
        char* fn;
        if (fabs(x) <= 1)
                fn = ("dat_x1.dat","r");
        if (x < -1)
                {
                x = 1/x;
                fn = ("dat_x2.dat","r");
                }
        if (x > 1)
                {
                x = 1/x;
                fn = ("dat_x3.dat","r");
                }
        fp = fopen(fn, "r");
        if (fp == NULL)
                throw "File can't be opened!";
        double temp;
        while (fscanf(fp,"%f",&temp) != EOF)
                {
                if (temp == x)
                        break;
                fscanf(fp,"%f",&temp);
                fscanf(fp,"%f",&temp);
                }
        if (temp == x)
                {
                fscanf(fp,"%f",&temp);
                fscanf(fp,"%f",&temp);
                fclose(fp);
                return temp;
                }
        else    {
                fclose(fp);
                temp = uu(x,fn);
                return temp;
                }
}
double uu(double x, char* fn)throw (char*)
{
        FILE *fp;
        if ( (fp=fopen(fn,"r")) == NULL)
                throw "File can't be opened!\n";
 
        double tempC, tempN; //current, next
        fscanf(fp,"%f",&tempN);
        tempC = tempN;
        fscanf(fp,"%f",&tempN);
        fscanf(fp,"%f",&tempN);
        while ( (fscanf(fp,"%f",&tempN)!=EOF) )
                {
                if ( (x > tempC) && (x<tempN) )
                        break;
                tempC = tempN;
                fscanf(fp,"%f",&tempN);
                fscanf(fp,"%f",&tempN);
                }
        if ( (x > tempC) && (x<tempN) )
                {
                fclose(fp);
                return  ( t(tempC) +  (x - tempC)/(tempN-tempC) );
                }
        else
                {cout<<"Error: Wrong x (func. tt)\n";
                 getch();
                 exit(1);}
}
double rrz2(double x, double y, double z)
{
        return (x>y)?   ( x*y*qrz2(y,z) ) : ( x*z*qrz2(x,y) );
}
double qrz2(double x, double y)
{
        return ( fabs(y)<1 )?   ( x*srs2(x,y,x) ): ( y*srs2(y,x,y) );
}
double srs2(double x, double y, double z)
{
        return ( z > y )? ( srz(x,y,z) + 1.44*y*z ) : ( y + 1.44*srz(z,x,y));
}
double rrz3(double x, double y, double z)
{
        return  ( x > y ) ? ( x*y*qrz3(y,z) ) : ( y*z*qrz3(x,y) );
}
double qrz3(double x, double y)
{
        return (fabs(x)< 1) ? ( x*srs3(x,y,x) ) : ( y*srs3(y,x,y) );
}
double srs3(double x, double y, double z)
{
        return ( z > y ) ? (srz(x,y,z) + y*x) : ( y*z + srz(z,x,y) );
}
Все функции, кроме t,tt,u,uu можно не рассматривать, так как там алгоритм типа: если переменная такая, то возвращаем такое, иначе возвращаем другое.

Пример содержания файла:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
0,000 -4,935  1,935    
0,050 -2,663  1,885     
0,100 -1,618  1,834    
0,150 -0,773  1,784    
0,200 -0,034  1,732    
0,250 0,635  1,679    
0,300 1,253  1,625    
0,350 1,829  1,570    
0,400 2,369  1,512    
0,450 2,877  1,452    
0,500 3,356  1,388    
0,550 3,806  1,322    
0,600 4,228  1,251    
0,650 4,622  1,175   
0,700 4,987  1,093    
0,750 5,320  1,003   
0,800 5,618  0,905    
0,850 5,876  0,796    
0,900 6,080  0,675    
0,950 6,199  0,536  
1,000 5,890  0,377
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
09.05.2011, 14:21
Ответы с готовыми решениями:

Форматированный ввод вывод массивов в и из файла txt
День добрый господа. Нужен ваш совет. Предположим что мне нужно создать 3 массива и переписать...

Как в C#.Net прочитать значения переменных из файла (подобно fscanf или scanf из C++) ?
Как в C#.Net прочитать значения переменных из файла (подобно fscanf или scanf из C++) ? Пример в...

Неправильно считывает 2 последних значения с файла
Здравия! Завтра дедлайн,а тут внезапно такая ошибка. Отказывается читать 2 последних значения с...

Написать программу которая считывает считывает текст из файла и записывает в другой слова состоящие не менее чем из 7 букв
Написать программу которая считывает считывает текст из файла и записывает в другой слова состоящие...

0
09.05.2011, 14:21
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
09.05.2011, 14:21
Помогаю со студенческими работами здесь

Чтение файла fscanf()
Доброго вечера! Если бы в файле были просто значения, в смысле : 10 10 50 90 30 30 50 10 60 29...

Fscanf, получение данных из файла
Добрый день, именно в С не особо силён, поэтому есть дурацкий вопрос :) Есть текстовый файл в...

Чтение из файла через fscanf
Файл такого содержания petrov 4305 5.000000 sidorov 4306 4.000000 пытаюсь записать в массив...

FSCANF и считывание слов из файла
Господа программисты и не только. У меня совсем простенький вопрос, но я уже не знаю, как самому на...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru