Почему у меня не работает функция atof?C ++ - PullRequest
0 голосов
/ 07 июля 2019

Я пытаюсь записать несколько векторов в файл, но функция atof вызывает у меня проблемы, и я не знаю, как их решить.До строки fscanf (читай, «% s% s \ n», s1, s2);для меня это не проблема, тогда да.



#include<iostream> 
#include<fstream> 
#include<string>
#include<stdlib.h>
#include <string.h>
#include <stdio.h>
#include<iomanip> 
#include<cmath>
using namespace std;

FILE *write,*read;

   double dz, pm ,xm, doub1,doub2;

   char s1[10],pz[10], s2[10],x[10], z[10];
int main(){
dz=0.00375;
   leer=fopen("data.dat","r");
   escribir=fopen("exitdata.dat","w+");//Donde vamos a escribir

   for(int a=0; a<5; a++){
        for(int i=0; i<10; i++){
            fscanf( read,"%s  %s \n", s1, s2);

//here begins the problem

            doub1 = atof(s1);
            doub2 = atof(s2);
            z[i]=(doub1+1)*dz;
            pz[i]=doub2;

            fprintf(escribir,"%s %s \n", s1,s2);
            cout<<z<<" "<<pz<<endl;


        }

        }

   fclose(escribir);//cerrar el archivo
   fclose(leer);


return 0;


}

1 Ответ

0 голосов
/ 08 июля 2019

Функция atof работает очень хорошо.

Но в целом в вашем коде много серьезных проблем.Прежде всего, и самое важное: код не может быть скомпилирован.Компилятор выкладывает много ошибок.И это показывает, что пошло не так.Поэтому, пожалуйста, запустите компилятор, прежде чем публиковать код со многими ошибками.

Затем я вижу тег C ++ - посмотрите ваши файлы заголовков.У многих есть «.h» в конце.Вы используете язык C за исключением одной строки: cout << z << " " << pz << endl;.И это тоже неправильно.Он не будет печатать, что вы ожидали.

Вы также не используете ни одного вектора здесь.И форматирование действительно плохое.

Позвольте мне сначала сделать краткий обзор кода:

#include<iostream> 
#include<fstream>       // *** Not used 
#include<string>        // *** Not used 
#include<stdlib.h>      // *** Not used
#include <string.h>     // *** Not used
#include <stdio.h
#include<iomanip>       // *** Not used 
#include<cmath>         // *** Not used
using namespace std;

FILE* write, * read;    // *** Major bug. You are not using this variables, instead you are using 'leer' and 'escribir'

double dz, pm, xm, doub1, doub2;
// *** Do not use plain arrays in C++. Never
char s1[10], pz[10], s2[10], x[10], z[10]; // *** You want to be pz and z strings!

int main() {
    dz = 0.00375;
    // *** fopen is deprecated in C++
    leer = fopen("data.dat", "r");       // *** Major bug. Variable leer has not been defined
    escribir = fopen("exitdata.dat", "w+");//Donde vamos a escribir  // *** Do not write spanish// *** Major bug. Variable escribir has not been defined

    for (int a = 0; a < 5; a++) {        // *** Why 2 loops? And "a" is never used. Maybe you wan to read 5 values?
        for (int i = 0; i < 10; i++) {   // *** Why this loop? You want to copy data in the char array.
                                         // *** You are now invoking the loop body 50times
            // *** fscanf is deprecated in C++
            fscanf(read, "%s  %s \n", s1, s2); // *** Read is a none initialize variabel System will crash.You opened leer

            //here begins the problem    // ** no, the problem began with trying fscanf on a none initialize file pointer

            doub1 = atof(s1);
            doub2 = atof(s2);
            z[i] = (doub1 + 1) * dz;  // Complier error. You are trying to assign a double to 1 char
            pz[i] = doub2;            // Complier error. You are trying to assign a double to 1 char

            fprintf(escribir, "%s %s \n", s1, s2);
            cout << z << " " << pz << endl;   // *** Will output nothing. You are passing an empty char[]


        }

    }

    fclose(escribir);//cerrar el archivo
    fclose(leer);


    return 0;


}

Так много ошибок и неправильное понимание C и C ++.Позвольте мне сделать код компилируемым.Но он все равно не будет делать то, что вы хотите, потому что у вас есть куча семантических ошибок.

Скомпилировано с MS Visual Studio 2019

#include<iostream> 
#include <stdio.h>

FILE* write, *read;

double dz, pm, xm, doub1, doub2;

char s1[10], pz[10], s2[10], x[10], z[10];

int main() 
{
    dz = 0.00375;
#pragma warning(suppress : 4996)
    read = fopen("r:\\data.dat", "r");
#pragma warning(suppress : 4996)
    write = fopen("r:\\exitdata.dat", "w+");

    for (int a = 0; a < 5; a++) {
        for (int i = 0; i < 10; i++) {
#pragma warning(suppress : 4996)
            fscanf(read, "%s  %s \n", s1, s2);
            doub1 = atof(s1);
            doub2 = atof(s2);
            //z[i] = (doub1 + 1) * dz; // No meaning
            //pz[i] = doub2;           // No meaning
            fprintf(write, "%s %s \n", s1, s2);
        }
    }
    fclose(write);
    fclose(read);
    return 0;
}

Конечно, это также не дает ожидаемого результата.

И, наконец, пример кода на C ++.Пожалуйста, прочитайте хорошую книгу по C ++.Пожалуйста, прочитайте об используемых функциях в cppreference.Пожалуйста, постарайтесь понять, строка за строкой.

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

struct TwoDoubles
{
    double doub1;
    double doub2;

    // Overwrite extractor  operator
    friend std::istream& operator >> (std::istream& is, TwoDoubles& td) {
        return is >> td.doub1 >> td.doub2;
    }
    // Overwrite inserter  operator
    friend std::ostream& operator << (std::ostream& os, const TwoDoubles& td) {
        return os << td.doub1 << ' ' << td.doub2;
    }
};

int main()
{
    // Open file with source data
    std::ifstream is("r:\\data.dat");

    // If file could be opened
    if (is) {

        // Open file containing results
        std::ofstream os("r:\\exitdata.dat");

        // If file could be opened
        if (os)
        {
            // Define a vector of doubles and initialize it
            std::vector<TwoDoubles> values{ std::istream_iterator<TwoDoubles>(is),std::istream_iterator<TwoDoubles>() };

            constexpr double dz = 0.00375;
            // Now we will calculate. Multiply all doubles with dz;
            std::for_each(values.begin(), values.end(), [dz](TwoDoubles & td) { td.doub1 = (td.doub1 + 1) * dz; });

            // Write everything to output file
            std::copy(values.begin(), values.end(), std::ostream_iterator<TwoDoubles>(os, "\n")) ;
        }
    }
    return 0;
}

Пожалуйста, продолжайте изучать

...