Модераторы: Partizan, gambit

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Проблема с чтением из файла в массив, Проблема с чтением из файла в массив 
:(
    Опции темы
voindozor2
Дата 5.7.2013, 10:51 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



По задумке программа должна записывать из формы 7 цифр в файл , и потом считывать их в numericUpDown  . 1ю задачу она выполняет , а вот во второй задаче при выводе в массив вместо чисел 1,2,3,4,5,6,7 выводит 32 и 10 все остальные числа в массиве пустые. Вот куски кода:
Самое начало программы:

Код
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<stdio.h>

#include "stdafx.h"
using namespace std;
#define BUFSIZE 8
char buffer [BUFSIZE];
namespace Картриджи {
int a10=0;
int a11=0;
int a12=0;
int a13=0;
int a14=0;
int a15=0;
int a16=0;
int a17=0;
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

1я кнопка которая работает :
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

int d1 = (int)this->numericUpDown1->Value;
int d2 = (int)this->numericUpDown2->Value;
int d3 = (int)this->numericUpDown3->Value;
int d4 = (int)this->numericUpDown4->Value;
int d5 = (int)this->numericUpDown5->Value;
int d6 = (int)this->numericUpDown6->Value;
int d7 = (int)this->numericUpDown7->Value;
int d8 = (int)this->numericUpDown8->Value;


  FILE *stream;
 
     /* открыть файл для изменения */
  stream = fopen("C:\\Users\\bilin.CS\\TextFile1.txt","w+");
  /* вывести в файл данные */
  fprintf(stream,"%d",d1);
  fprintf(stream,"%d ",d2);
  fprintf(stream,"%d ",d3);
  fprintf(stream,"%d ",d4);
  fprintf(stream,"%d ",d5);
  fprintf(stream,"%d ",d6);
  fprintf(stream,"%d ",d7);
  fprintf(stream,"%d ",d8);
  /* закрыть файл */
  fclose(stream);
  
  if(stream == NULL){
  perror("Couldn't open file: C:\\ro_apps\\IandQ.csv\n");
  return;
  

}

2я кнопка которая работает неправильно:
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
FILE *stream;
stream = fopen("C:\\Users\\bilin\\TextFile1.txt","r");

if(stream)
{
while(!feof(stream))
{
fgets(buffer, BUFSIZE, stream);


}


a10= buffer[1];
a11= buffer[2];
a12= buffer[3];
a13= buffer[4];
a14= buffer[5];
a15= buffer[6];
a16= buffer[7];
a17= buffer[8];
this->numericUpDown1->Value = a10;
this->numericUpDown2->Value = a11;
this->numericUpDown3->Value = a12;
this->numericUpDown4->Value = a13;
this->numericUpDown5->Value = a14;
this->numericUpDown6->Value = a15;
this->numericUpDown7->Value = a16;
this->numericUpDown8->Value = a17;


}


Прошу , помогите пожалуйста , уже 2й день бьюсь над ней)

Модератор: не забываем пользоваться кнопочкой "Код"
PM MAIL   Вверх
volatile
Дата 5.7.2013, 11:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 2107
Регистрация: 7.1.2011

Репутация: нет
Всего: 85



Цитата(voindozor2 @  5.7.2013,  10:51 Найти цитируемый пост)
  fprintf(stream,"%d ",d3);

Цитата(voindozor2 @  5.7.2013,  10:51 Найти цитируемый пост)
fgets(buffer, BUFSIZE, stream);


Если писали fprintf(), читать нужно соответственно fscanf()
PM MAIL   Вверх
SenkraD
Дата 5.7.2013, 11:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 933
Регистрация: 3.2.2006
Где: Украина::Киев

Репутация: нет
Всего: 23



Если розбираться в вашем решении, то причина в вашей функции которая читает (там тихий ужас непонимания с вашей  стороны на тему что и как работает) и отсутствие сепараторов в функции сохранения (хотя могу ошибатьться и это не обязательно)

ну вцелом вот вам решении на С++, а над вашим сейчас покурю, где собственно и будем использовать fscan, о котором и говорил  volatile:
Код

//--------------------------------------------------------------------------------------------------
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>

//--------------------------------------------------------------------------------------------------
void save(std::vector<int> const& data, std::string const& fileName) 
{
    std::ofstream file(fileName.c_str(), std::ios::out | std::ios::trunc);
    std::copy(
          data.begin()
        , data.end()
        , std::ostream_iterator<int>(file, "\r\n")
    );
}

std::vector<int> read(std::string const& fileName) 
{
    std::ifstream file(fileName.c_str());

    std::vector<int> result;
    std::copy(
          std::istream_iterator<int>(file)
        , std::istream_iterator<int>()
        , std::back_inserter(result)
    );
    return result;
}

//--------------------------------------------------------------------------------------------------
//
//
int main(int argc, char* argv[])
{
    std::string fileName("data.dat");
    std::vector<int> data;
    {
        data.push_back(1);
        data.push_back(11);
        data.push_back(5);
        data.push_back(9);
        data.push_back(111);
        data.push_back(33);
        data.push_back(44);
    }

    // print our array
    {
        std::cout << "Array: ";
        std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, "\r\n"));
        std::cout << std::endl;
    }

    
    save(data, fileName);
    {
        std::vector<int> savedData = read(fileName);
        {
            std::cout << "Loaded array: ";
            std::copy(savedData.begin(), savedData.end(), std::ostream_iterator<int>(std::cout, "\r\n"));
            std::cout << std::endl;
        }
    }

    std::cin.peek();
    return 0;
}


Это сообщение отредактировал(а) SenkraD - 5.7.2013, 11:40


--------------------
 Имеющий язык - да не убоится спросить! 
user posted image
PM MAIL ICQ   Вверх
voindozor2
Дата 5.7.2013, 11:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



Спасибо , щас попробую разобраться в данном решении...


Это сообщение отредактировал(а) voindozor2 - 5.7.2013, 11:46
PM MAIL   Вверх
SenkraD
Дата 5.7.2013, 11:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 933
Регистрация: 3.2.2006
Где: Украина::Киев

Репутация: нет
Всего: 23



Вот функции save и read переписанные на fprintf и fscan:
Код

void save(std::vector<int> data, std::string const& fileName) 
{
    FILE* stream = std::fopen(fileName.c_str(), "w+");
    for (std::size_t i = 0, count = data.size(); i < count; ++i)
    {
        std::fprintf(stream, "%d ",  data[i]);
    }
    std::fclose(stream);
}

std::vector<int> read(std::string const& fileName) 
{
    std::vector<int> result;

    int buffer = 0;
    FILE* stream = std::fopen(fileName.c_str(), "r");
    while (std::fscanf(stream, "%d", &buffer) != EOF)
    {
        result.push_back(buffer);
    }
    std::fclose(stream);
    return result;
}


Это сообщение отредактировал(а) SenkraD - 5.7.2013, 11:45


--------------------
 Имеющий язык - да не убоится спросить! 
user posted image
PM MAIL ICQ   Вверх
voindozor2
Дата 5.7.2013, 11:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



Спасибо за помощь сейчас попробую что то сделать )

PM MAIL   Вверх
volatile
Дата 5.7.2013, 11:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 2107
Регистрация: 7.1.2011

Репутация: нет
Всего: 85



Цитата(SenkraD @  5.7.2013,  11:32 Найти цитируемый пост)
 fscan, о котором и говорил  volatile:

SenkraD,  ваш первый вариант с С++ потоками, более кошерный, не нужно уже было fscanf  smile 
(я просто подсказал минимальный вариант изменений, чтобы просто заработало).

PM MAIL   Вверх
voindozor2
Дата 5.7.2013, 12:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



Дело в том что я работаю в Visual studio 2010 express и хотелось бы задать несколько вопросов , using namespace std присутствует в моем коде , но пишет 1>c:\users\bilin.cs\documents\visual studio 2010\projects\картриджи\картриджи\Form1.h(371): error C2039: vector: не является членом "std"


1>c:\users\bilin.cs\documents\visual studio 2010\projects\картриджи\картриджи\Form1.h(375): error C2228: выражение слева от ".c_str" должно представлять класс, структуру или объединение
1>          тип: const char [29]

1>c:\users\bilin.cs\documents\visual studio 2010\projects\картриджи\картриджи\Form1.h(378): error C2228: выражение слева от ".push_back" должно представлять класс, структуру или объединение
1>          тип: 'unknown-type'


PM MAIL   Вверх
SenkraD
Дата 5.7.2013, 12:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 933
Регистрация: 3.2.2006
Где: Украина::Киев

Репутация: нет
Всего: 23



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


--------------------
 Имеющий язык - да не убоится спросить! 
user posted image
PM MAIL ICQ   Вверх
voindozor2
Дата 5.7.2013, 12:10 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



Все , извините за беспокойство разобрался с этими ошибками)

Добавлено через 38 секунд
Да , буду разбираться) Спасибо за помощь)

PM MAIL   Вверх
voindozor2
Дата 5.7.2013, 12:38 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



Еще 1 вопрос , ведь вы мне написали пример функции в целом , но т.к я пытаюсь это все засунуть в функцию кнопки на форме , вылезает ошибка error C2601: read: недопустимые локальные определения функций.
Как я понял эта ошибка возникает когда функция внутри еще 1 функции есть. 
Как бы это тогда сделать так , чтобы все работало и без ошибки?)

PM MAIL   Вверх
SenkraD
Дата 5.7.2013, 12:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 933
Регистрация: 3.2.2006
Где: Украина::Киев

Репутация: нет
Всего: 23



покажите код, не забыв использовать кнопочку код (Ctrl + Shift + C)


--------------------
 Имеющий язык - да не убоится спросить! 
user posted image
PM MAIL ICQ   Вверх
voindozor2
Дата 5.7.2013, 12:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



Код

#pragma once

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<stdio.h>
#include <vector>
#include "stdafx.h"
using namespace std;
#define BUFSIZE 1024
//char buffer [BUFSIZE];
namespace Картриджи {
    int a10=0;
    int a11=0;
    int a12=0;
    int a13=0;
    int a14=0;
    int a15=0;
    int a16=0;
    int a17=0;
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;


    /// <summary>
    /// Сводка для Form1
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
        }

    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::MonthCalendar^  monthCalendar1;
    private: System::Windows::Forms::TextBox^  textBox1;
    private: System::Windows::Forms::TextBox^  textBox2;
    private: System::Windows::Forms::TextBox^  textBox3;
    private: System::Windows::Forms::TextBox^  textBox4;
    private: System::Windows::Forms::TextBox^  textBox5;
    private: System::Windows::Forms::TextBox^  textBox6;
    private: System::Windows::Forms::TextBox^  textBox7;
    private: System::Windows::Forms::TextBox^  textBox8;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown1;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown2;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown3;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown4;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown5;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown6;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown7;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown8;
    private: System::Windows::Forms::Button^  button2;

    protected: 

    private:
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Обязательный метод для поддержки конструктора - не изменяйте
        /// содержимое данного метода при помощи редактора кода.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->monthCalendar1 = (gcnew System::Windows::Forms::MonthCalendar());
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->textBox2 = (gcnew System::Windows::Forms::TextBox());
            this->textBox3 = (gcnew System::Windows::Forms::TextBox());
            this->textBox4 = (gcnew System::Windows::Forms::TextBox());
            this->textBox5 = (gcnew System::Windows::Forms::TextBox());
            this->textBox6 = (gcnew System::Windows::Forms::TextBox());
            this->textBox7 = (gcnew System::Windows::Forms::TextBox());
            this->textBox8 = (gcnew System::Windows::Forms::TextBox());
            this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown2 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown3 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown4 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown5 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown6 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown7 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown8 = (gcnew System::Windows::Forms::NumericUpDown());
            this->button2 = (gcnew System::Windows::Forms::Button());
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown1))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown2))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown3))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown4))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown5))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown6))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown7))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown8))->BeginInit();
            this->SuspendLayout();
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(291, 377);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(119, 44);
            this->button1->TabIndex = 0;
            this->button1->Text = L"Обновить";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            // 
            // monthCalendar1
            // 
            this->monthCalendar1->Location = System::Drawing::Point(573, 0);
            this->monthCalendar1->Name = L"monthCalendar1";
            this->monthCalendar1->TabIndex = 1;
            // 
            // textBox1
            // 
            this->textBox1->Enabled = false;
            this->textBox1->Location = System::Drawing::Point(99, 43);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(100, 20);
            this->textBox1->TabIndex = 2;
            this->textBox1->Text = L"Hello";
            this->textBox1->TextChanged += gcnew System::EventHandler(this, &Form1::textBox1_TextChanged);
            // 
            // textBox2
            // 
            this->textBox2->Enabled = false;
            this->textBox2->Location = System::Drawing::Point(99, 69);
            this->textBox2->Name = L"textBox2";
            this->textBox2->Size = System::Drawing::Size(100, 20);
            this->textBox2->TabIndex = 3;
            this->textBox2->Text = L"Hello";
            // 
            // textBox3
            // 
            this->textBox3->Enabled = false;
            this->textBox3->Location = System::Drawing::Point(99, 95);
            this->textBox3->Name = L"textBox3";
            this->textBox3->Size = System::Drawing::Size(100, 20);
            this->textBox3->TabIndex = 4;
            this->textBox3->Text = L"Hello";
            // 
            // textBox4
            // 
            this->textBox4->Enabled = false;
            this->textBox4->Location = System::Drawing::Point(99, 121);
            this->textBox4->Name = L"textBox4";
            this->textBox4->Size = System::Drawing::Size(100, 20);
            this->textBox4->TabIndex = 5;
            this->textBox4->Text = L"Hello";
            // 
            // textBox5
            // 
            this->textBox5->Enabled = false;
            this->textBox5->Location = System::Drawing::Point(99, 147);
            this->textBox5->Name = L"textBox5";
            this->textBox5->Size = System::Drawing::Size(100, 20);
            this->textBox5->TabIndex = 6;
            this->textBox5->Text = L"Hello";
            // 
            // textBox6
            // 
            this->textBox6->Enabled = false;
            this->textBox6->Location = System::Drawing::Point(99, 173);
            this->textBox6->Name = L"textBox6";
            this->textBox6->Size = System::Drawing::Size(100, 20);
            this->textBox6->TabIndex = 7;
            this->textBox6->Text = L"Hello";
            // 
            // textBox7
            // 
            this->textBox7->Enabled = false;
            this->textBox7->Location = System::Drawing::Point(99, 199);
            this->textBox7->Name = L"textBox7";
            this->textBox7->Size = System::Drawing::Size(100, 20);
            this->textBox7->TabIndex = 8;
            this->textBox7->Text = L"Hello";
            // 
            // textBox8
            // 
            this->textBox8->Enabled = false;
            this->textBox8->Location = System::Drawing::Point(99, 225);
            this->textBox8->Name = L"textBox8";
            this->textBox8->Size = System::Drawing::Size(100, 20);
            this->textBox8->TabIndex = 9;
            this->textBox8->Text = L"Hello";
            // 
            // numericUpDown1
            // 
            this->numericUpDown1->Location = System::Drawing::Point(261, 42);
            this->numericUpDown1->Name = L"numericUpDown1";
            this->numericUpDown1->Size = System::Drawing::Size(120, 20);
            this->numericUpDown1->TabIndex = 10;
            // 
            // numericUpDown2
            // 
            this->numericUpDown2->Location = System::Drawing::Point(261, 68);
            this->numericUpDown2->Name = L"numericUpDown2";
            this->numericUpDown2->Size = System::Drawing::Size(120, 20);
            this->numericUpDown2->TabIndex = 11;
            // 
            // numericUpDown3
            // 
            this->numericUpDown3->Location = System::Drawing::Point(261, 96);
            this->numericUpDown3->Name = L"numericUpDown3";
            this->numericUpDown3->Size = System::Drawing::Size(120, 20);
            this->numericUpDown3->TabIndex = 12;
            // 
            // numericUpDown4
            // 
            this->numericUpDown4->Location = System::Drawing::Point(261, 121);
            this->numericUpDown4->Name = L"numericUpDown4";
            this->numericUpDown4->Size = System::Drawing::Size(120, 20);
            this->numericUpDown4->TabIndex = 13;
            // 
            // numericUpDown5
            // 
            this->numericUpDown5->Location = System::Drawing::Point(261, 147);
            this->numericUpDown5->Name = L"numericUpDown5";
            this->numericUpDown5->Size = System::Drawing::Size(120, 20);
            this->numericUpDown5->TabIndex = 14;
            // 
            // numericUpDown6
            // 
            this->numericUpDown6->Location = System::Drawing::Point(261, 174);
            this->numericUpDown6->Name = L"numericUpDown6";
            this->numericUpDown6->Size = System::Drawing::Size(120, 20);
            this->numericUpDown6->TabIndex = 15;
            // 
            // numericUpDown7
            // 
            this->numericUpDown7->Location = System::Drawing::Point(261, 199);
            this->numericUpDown7->Name = L"numericUpDown7";
            this->numericUpDown7->Size = System::Drawing::Size(120, 20);
            this->numericUpDown7->TabIndex = 16;
            // 
            // numericUpDown8
            // 
            this->numericUpDown8->Location = System::Drawing::Point(261, 225);
            this->numericUpDown8->Name = L"numericUpDown8";
            this->numericUpDown8->Size = System::Drawing::Size(120, 20);
            this->numericUpDown8->TabIndex = 17;
            // 
            // button2
            // 
            this->button2->Location = System::Drawing::Point(480, 377);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(129, 43);
            this->button2->TabIndex = 18;
            this->button2->Text = L"Считывание";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(737, 446);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->numericUpDown8);
            this->Controls->Add(this->numericUpDown7);
            this->Controls->Add(this->numericUpDown6);
            this->Controls->Add(this->numericUpDown5);
            this->Controls->Add(this->numericUpDown4);
            this->Controls->Add(this->numericUpDown3);
            this->Controls->Add(this->numericUpDown2);
            this->Controls->Add(this->numericUpDown1);
            this->Controls->Add(this->textBox8);
            this->Controls->Add(this->textBox7);
            this->Controls->Add(this->textBox6);
            this->Controls->Add(this->textBox5);
            this->Controls->Add(this->textBox4);
            this->Controls->Add(this->textBox3);
            this->Controls->Add(this->textBox2);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->monthCalendar1);
            this->Controls->Add(this->button1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown1))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown2))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown3))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown4))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown5))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown6))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown7))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown8))->EndInit();
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             }

private: System::Void textBox1_TextChanged(System::Object^  sender, System::EventArgs^  e) {
         }

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
        
int d1 = (int)this->numericUpDown1->Value;
int d2 = (int)this->numericUpDown2->Value;
int d3 = (int)this->numericUpDown3->Value;
int d4 = (int)this->numericUpDown4->Value;
int d5 = (int)this->numericUpDown5->Value;
int d6 = (int)this->numericUpDown6->Value;
int d7 = (int)this->numericUpDown7->Value;
int d8 = (int)this->numericUpDown8->Value;


   FILE *stream;
  
      /* открыть файл для изменения */
   stream = fopen("C:\\Users\\bilin.CS\\TextFile1.txt","w+");
   /* вывести в файл данные */
   fprintf(stream,"%d",d1);
   fprintf(stream,"%d ",d2);
   fprintf(stream,"%d ",d3);
   fprintf(stream,"%d ",d4);
   fprintf(stream,"%d ",d5);
   fprintf(stream,"%d ",d6);
   fprintf(stream,"%d ",d7);
   fprintf(stream,"%d ",d8);
   /* закрыть файл */
   fclose(stream);
   
   if(stream == NULL){
   perror("Couldn't open file: C:\\ro_apps\\IandQ.csv\n");
   return;
   

}
    
             
             }
private: System::Void listBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {
         }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
/*FILE *stream;
stream = fopen("C:\\Users\\bilin\\TextFile1.txt","r");

if(stream)
{
while(!feof(stream))
{
fgets(buffer, BUFSIZE, stream);


}

*/
             
char* filename="C:\\Users\\bilin\\TextFile1.txt";

std::vector<int> read(std::string const& filename ) {

    std::vector<int> result;
    int buffer = 0;
    FILE* stream = std::fopen(filename.c_str(), "r");
    while (std::fscanf(stream, "%d", &buffer) != EOF)
    {
        result.push_back(buffer);
    }
    std::fclose(stream);
   return result;
}







/*
a10= buffer[1];
a11= buffer[2];
a12= buffer[3];
a13= buffer[4];
a14= buffer[5];
a15= buffer[6];
a16= buffer[7];
a17= buffer[8];

this->numericUpDown1->Value = a10;
this->numericUpDown2->Value = a11;
this->numericUpDown3->Value = a12;
this->numericUpDown4->Value = a13;
this->numericUpDown5->Value = a14;
this->numericUpDown6->Value = a15;
this->numericUpDown7->Value = a16;
this->numericUpDown8->Value = a17;
*/

}
};


}




Добавлено через 36 секунд
строка 374 ошибку пишет
PM MAIL   Вверх
SenkraD
Дата 5.7.2013, 12:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 933
Регистрация: 3.2.2006
Где: Украина::Киев

Репутация: нет
Всего: 23



перенесите ее с 374 на позиции между 19 и 20 строками и должно будет быть вам счастье или сделайте ее методом вашей формы, но лучше не нужно smile
Код

//...
    int a17=0;

    std::vector<int> read(std::string const& filename ) {
        std::vector<int> result;
        int buffer = 0;
        FILE* stream = std::fopen(filename.c_str(), "r");
        while (std::fscanf(stream, "%d", &buffer) != EOF)
        {
            result.push_back(buffer);
        }
        std::fclose(stream);
        return result;
    }

    using namespace System;
//...
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
    char const* const filename="C:\\Users\\bilin\\TextFile1.txt";
    std::vector<int> data = read(filename);

    this->numericUpDown1->Value = data[0];
    this->numericUpDown2->Value = data[1];
    this->numericUpDown3->Value = data[2];
    this->numericUpDown4->Value = data[3];
    this->numericUpDown5->Value = data[4];
    this->numericUpDown6->Value = data[5];
    this->numericUpDown7->Value = data[6];
    this->numericUpDown8->Value = data[7];
}
//...


Это сообщение отредактировал(а) SenkraD - 5.7.2013, 13:03


--------------------
 Имеющий язык - да не убоится спросить! 
user posted image
PM MAIL ICQ   Вверх
voindozor2
Дата 5.7.2013, 13:23 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 17.4.2012

Репутация: нет
Всего: нет



К сожалению в между 19-20 строками не выходит .
PM MAIL   Вверх
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
Partizan
PashaPash

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, Partizan, PashaPash.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | .NET для новичков | Следующая тема »


 




[ Время генерации скрипта: 0.1027 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.