Avatar billede henrik10 Nybegynder
17. maj 2002 - 04:14 Der er 8 kommentarer og
2 løsninger

Datafile

Hej,
Jeg skal lave en text file med foelgende integers
2  13  48  90  23  44  88  45  97  32  48  97  67  453
Jeg lavede derfor en i notepad og kaldte den "datafile", men det virker ikke. Er der en der kan gennemskue hvad jeg goer galt og hvordan jeg kan faa loest dette proble. Jeg har pastet mit program saa i har mulighed for at compile det. Der mangler jo saa textfilen. Det er paakraevet at jeg bruger:
#define  DATAFILE "datafile.txt"

Paa forhaand tak!





#include <iostream.h>                        // for input and output statements
#include <fstream.h>                        // for reading from and writing to a file

#define  DATAFILE "datafile.txt"            // the file containing integer numbers

const int MAX_LEN = 50;                        // maximum number of elements
const char BLANK = ' ';                        // used for a dummy character
const int DONT_CARE = 0;                    // used for a dummy integer variable
const int SO_MANY_CHARS = 100;                // to be used with ignor() to skip blanks

enum message_type {OPENING,CLOSING,UNKNOWN_CHAR, NOT_FOUND,POSITION_IN_LIST,WARNING};

//==========================================================================================
//                                    prototypes
//==========================================================================================

void print_message(message_type sttm, char ch, int val, int pos);
void fill_list(ifstream &infile, int list[], int& len);
void print_list (const int list[], int len);
void get_menu_item (char& ans);
void get_value (int& val);
int  find_position(const int list[],int len, int val);
void delete_value (int list[],int& len,int index);

//******************************************************************************************
//                                    main()
//******************************************************************************************

void main()
{

    int list[MAX_LEN];        // the list for holding up to MAX_LEN numbers
    int length;                // number of elements of the array
    int value;                // value to be deleted from the list entered by the user
    int index;                // the index to the value to be deleted in the list
    char answer;            // answer to the query enterd by the user

    ifstream infile;        //input file stream


    infile.open(DATAFILE,ios::in|ios::nocreate);    //open datafile for reading
    if (infile.fail())
        cout<<"*** Can't open the file**"<<endl;
    else
    {   
        print_message(OPENING,BLANK,DONT_CARE,DONT_CARE);

        fill_list (infile,list,length);

        print_list(list, length);

        do
        {
            get_menu_item(answer);

            switch (answer)
            {
                case 'd': get_value (value);
                          index= find_position (list, length, value);
                          if (index<0)            // value not found
                                print_message(NOT_FOUND,BLANK, value,DONT_CARE );
                          else
                          {
                                print_message(POSITION_IN_LIST,BLANK, value,index+1); //add one to index to be user friendly
                                delete_value (list, length, index);
                                print_list(list, length);
                          }
                          break;

                case 'q': print_message(CLOSING,BLANK,DONT_CARE,DONT_CARE);
                          break;

                default:  print_message (UNKNOWN_CHAR,answer,DONT_CARE,DONT_CARE);
                          break; //not necessary but a good habit
            }//switch
           
        } while (answer != 'q');
       

        infile.close();
    }
   
}
//******************************************************************************************
//                                    print_message()
// This function writes messages on the screen.
//******************************************************************************************
void print_message(/*in*/  message_type sttm,    //type of message
                    /*in*/  char ch,            //used with UNKNOWN_CHAR message
                    /*in*/  int val,            //used with NOT_FOUND and POSITION_INLIST message
                    /*in*/  int pos)            //used with POSITION_INLIST message
{
    switch (sttm)
    {
    case UNKNOWN_CHAR: cout<<"=======> Sorry I don't understand what "<<'"'<<ch<<'"'<< " means\n";
                      break;

    case NOT_FOUND:    cout<<"=======> Sorry "<<val<<" is not in the list\n";
                      break;

    case OPENING:      cout<<"This program deletes a number form a given list for you.  "
                            <<"Here is the list (read from a file):\n";
                      break;

    case CLOSING:      cout<<"***********************************************************\n";
                      cout<<"      Thanks for choosing our program and bye now.\n";
                      cout<<"***********************************************************\n";
                      break;

    case POSITION_IN_LIST:     
                      cout<<"The first occurance of the value "<<"("<<val<<")"<< " is at position ";
                      cout<<pos<<endl;
                      break;

    case WARNING:      cout<<"----Warning---> The file contains more than " << MAX_LEN<<" elements. ";
                      cout<<"Only the first "<< MAX_LEN<<" elements will be processed.\n";
                      break;//UNNECESSARY BUT A GOOD HABIT

    }

}
//******************************************************************************************
//                                        fill_list()
// This function fills up the array with numbers in the file.  If the file contains
// more than MAX_LEN numbers only the first MAX_LEN numbers will be processed.
//******************************************************************************************
void fill_list(/* in*/ ifstream &infile,//contains the numbers
              /*out*/ int list[],        //for holding the numbers
              /*out*/ int& len)        //length of the list
{
    int buffer;
    len =0;
    infile >> buffer;
    while (infile && len< MAX_LEN)
    {
        list[len]=buffer;
        len++;
        infile >>buffer;
    }
    //if (infile)
}
//******************************************************************************************
//                                        print_list()
// This function prints the elements of the array.
//******************************************************************************************
void print_list (/* in*/ const int list[],    // the list
                /*in*/ int len)            // number of elements stored in the array

{
    int curr_index;
    for (curr_index =0; curr_index<len; curr_index++)
    {
        cout << list [curr_index]<<endl;
    }
}

//******************************************************************************************
//                                        get_menu_item()
// This function gets a menu item from the user.
//******************************************************************************************
void get_menu_item (/*out*/ char& ans)        // d for delete and q for quit
{
    cout<< "Would you like to [d]elete a value or [q]uit the program?";
    cin >> ans;
    cin.ignore(SO_MANY_CHARS,'\n');                    //ignore the rest of the line
    cout<<endl;
}
//******************************************************************************************
//                                        get_value()
// This function gets an integer number from the user.
//******************************************************************************************
void get_value (/*out*/ int& val)        // an integer number to be deleted from the list
{
    cout<< "Enter the value you wish to delete: ";
    cin >> val;
    cin.ignore(SO_MANY_CHARS,'\n');                //ignore the rest of the line
    cout<<endl;
}
//******************************************************************************************
//                                        find_position()
// This function finds the postion of the value in the list, if found.  if the value is not
// in the list it returns -1.
//******************************************************************************************
int find_position(/*in*/ const int list[],    // the list to be searched
                        int len,            // the lenght of the list
                        int val)            // the vlaue to be looked up
{
    bool found=false;
    int curr_pos=0;
    while ((len< MAX_LEN) && (!found))
    {
        if (list[curr_pos]== val)
            found=true;
        else
            curr_pos++;
    }
    if (found)
   
        return curr_pos;
    else 
        return -1;
   

    return 0;                                // this statement must be replaced by the body
                                            // of the function
}
//******************************************************************************************
//                                        delete_value()
// This function deletes the value from the list.  Note that it is assumed the value is in
// the list.
//******************************************************************************************
void delete_value (/*out*/ int list[],        //the list to be modified
                  /*out*/ int& len,        // length of the list
                  /*in*/  int index)        // the index of the value to be deleted
{
    int pos;
    int curr_pos;
    int last_index;
    curr_pos= pos;
    last_index=len-1;
    while (curr_pos <last_index -1)
    {
        list[curr_pos]=list[curr_pos + 1];
    }
    len++;
}
Avatar billede chries Nybegynder
17. maj 2002 - 09:35 #1
har rettet følgende:
cin.ignore fjernet (kunne ikke indtaste)
find_value modificeret (gik ned når den ikke var i listen)
delete value modificeret (værdi ikke initieret, forkert brug ved len -1, last_index -1 og len++ talte længde op)



#include <iostream.h>                        // for input and output statements
#include <fstream.h>                        // for reading from and writing to a file

#define  DATAFILE "datafile.txt"            // the file containing integer numbers

const int MAX_LEN = 50;                        // maximum number of elements
const char BLANK = ' ';                        // used for a dummy character
const int DONT_CARE = 0;                    // used for a dummy integer variable
const int SO_MANY_CHARS = 100;                // to be used with ignor() to skip blanks

enum message_type {OPENING,CLOSING,UNKNOWN_CHAR, NOT_FOUND,POSITION_IN_LIST,WARNING};

//==========================================================================================
//                                    prototypes
//==========================================================================================

void print_message(message_type sttm, char ch, int val, int pos);
void fill_list(ifstream &infile, int list[], int& len);
void print_list (const int list[], int len);
void get_menu_item (char& ans);
void get_value (int& val);
int  find_position(const int list[],int len, int val);
void delete_value (int list[],int& len,int index);

//******************************************************************************************
//                                    main()
//******************************************************************************************

void main()
{

    int list[MAX_LEN];        // the list for holding up to MAX_LEN numbers
    int length;                // number of elements of the array
    int value;                // value to be deleted from the list entered by the user
    int index;                // the index to the value to be deleted in the list
    char answer;            // answer to the query enterd by the user

    ifstream infile;        //input file stream


    infile.open(DATAFILE,ios::in|ios::nocreate);    //open datafile for reading
    if (infile.fail())
        cout<<"*** Can't open the file**"<<endl;
    else
    {   
        print_message(OPENING,BLANK,DONT_CARE,DONT_CARE);

        fill_list (infile,list,length);

        print_list(list, length);

        do
        {
            get_menu_item(answer);

            switch (answer)
            {
                case 'd': get_value (value);
                          index= find_position (list, length, value);
                          if (index<0)            // value not found
                                print_message(NOT_FOUND,BLANK, value,DONT_CARE );
                          else
                          {
                                print_message(POSITION_IN_LIST,BLANK, value,index+1); //add one to index to be user friendly
                                delete_value (list, length, index);
                                print_list(list, length);
                          }
                          break;

                case 'q': print_message(CLOSING,BLANK,DONT_CARE,DONT_CARE);
                          break;

                default:  print_message (UNKNOWN_CHAR,answer,DONT_CARE,DONT_CARE);
                          break; //not necessary but a good habit
            }//switch
           
        } while (answer != 'q');
       

        infile.close();
    }
   
}
//******************************************************************************************
//                                    print_message()
// This function writes messages on the screen.
//******************************************************************************************
void print_message(/*in*/  message_type sttm,    //type of message
                    /*in*/  char ch,            //used with UNKNOWN_CHAR message
                    /*in*/  int val,            //used with NOT_FOUND and POSITION_INLIST message
                    /*in*/  int pos)            //used with POSITION_INLIST message
{
    switch (sttm)
    {
    case UNKNOWN_CHAR: cout<<"=======> Sorry I don't understand what "<<'"'<<ch<<'"'<< " meansn";
                      break;

    case NOT_FOUND:    cout<<"=======> Sorry "<<val<<" is not in the listn";
                      break;

    case OPENING:      cout<<"This program deletes a number form a given list for you.  "
                            <<"Here is the list (read from a file):" << endl;
                      break;

    case CLOSING:      cout<<"***********************************************************n";
                      cout<<"      Thanks for choosing our program and bye now.n";
                      cout<<"***********************************************************n";
                      break;

    case POSITION_IN_LIST:     
                      cout<<"The first occurance of the value "<<"("<<val<<")"<< " is at position ";
                      cout<<pos<<endl;
                      break;

    case WARNING:      cout<<"----Warning---> The file contains more than " << MAX_LEN<<" elements. ";
                      cout<<"Only the first "<< MAX_LEN<<" elements will be processed.n";
                      break;//UNNECESSARY BUT A GOOD HABIT

    }

}
//******************************************************************************************
//                                        fill_list()
// This function fills up the array with numbers in the file.  If the file contains
// more than MAX_LEN numbers only the first MAX_LEN numbers will be processed.
//******************************************************************************************
void fill_list(/* in*/ ifstream &infile,//contains the numbers
              /*out*/ int list[],        //for holding the numbers
              /*out*/ int& len)        //length of the list
{
    int buffer;
    len =0;
    infile >> buffer;
    while (infile && len< MAX_LEN)
    {
        list[len]=buffer;
        len++;
        infile >>buffer;
    }
    //if (infile)
}
//******************************************************************************************
//                                        print_list()
// This function prints the elements of the array.
//******************************************************************************************
void print_list (/* in*/ const int list[],    // the list
                /*in*/ int len)            // number of elements stored in the array

{
    int curr_index;
    for (curr_index =0; curr_index<len; curr_index++)
    {
        cout << list [curr_index]<<endl;
    }
}

//******************************************************************************************
//                                        get_menu_item()
// This function gets a menu item from the user.
//******************************************************************************************
void get_menu_item (/*out*/ char& ans)        // d for delete and q for quit
{
    cout<< "Would you like to [d]elete a value or [q]uit the program?";

    cin >> ans;
    cout << endl;   
}
//******************************************************************************************
//                                        get_value()
// This function gets an integer number from the user.
//******************************************************************************************
void get_value (/*out*/ int& val)        // an integer number to be deleted from the list
{
    cout<< "Enter the value you wish to delete: ";
    cin >> val;
    cout<<endl;
}
//******************************************************************************************
//                                        find_position()
// This function finds the postion of the value in the list, if found.  if the value is not
// in the list it returns -1.
//******************************************************************************************
int find_position(/*in*/ const int list[],    // the list to be searched
                        int len,            // the lenght of the list
                        int val)            // the vlaue to be looked up
{
    bool found=false;
    int curr_pos=0;
   
    if( len > MAX_LEN )
    {
        return -1;
    }

    for( int i=0; i<len; i++ )
    {
        if( list[i] == val )
        {
            return i;
        }
    }

    return -1; 

}
//******************************************************************************************
//                                        delete_value()
// This function deletes the value from the list.  Note that it is assumed the value is in
// the list.
//******************************************************************************************
void delete_value (/*out*/ int list[],        //the list to be modified
                  /*out*/ int& len,        // length of the list
                  /*in*/  int index)        // the index of the value to be deleted
{
    int curr_pos;
    int last_index;
    curr_pos = index;
    last_index = len;
    for( int i = index; i < last_index; i++ )
    {
        list[i]=list[i + 1];
    }
    len--;
}
Avatar billede chries Nybegynder
17. maj 2002 - 09:36 #2
Ser ud til at virke.
Avatar billede mbulow Nybegynder
17. maj 2002 - 10:35 #3
Hejsa

Nu har jeg godt nok ikke arbejdet mig gennem hele din kode, men jeg har dog kigget nok på den til at se at du, naturligt nok, arbejder med alle dine værdier som int's.

Problemet er bare at din datafil IKKE indeholder int's (32bit til første tal, 32bit il næste tal, osv.). Den indeholder en masse tal repræsenteret som strenge, og separeret med mellemrum.

Det du skal gøre for at få konverteret værdierne i din "tekst"-datafil til nogle frnuftige integers, er at indlæse EN strengværdi af gangen, konvertere den til en int, tilføje den til listen og gentage så længe du ikke er nået til enden af filen.

Her har du et lille stykke kode der indlæser en tekstfil ligesom din, konverterer de indlæste strengværdier til tal, og udskriver strengværdi og tal, så du kan se de er ens:

#include <fstream>
#include <iostream.h>
#include <string>
using namespace std;

int main(int argc, char *argv[]){
    ifstream ifs;
    string str;
    int i;

    ifs.open("C:\\Temporary\\Data.txt");
    while(!ifs.eof()){
        getline(ifs, str, ' ');
        i = atoi(str.c_str());
        cout << str.c_str() << " == " << i << endl;
    }
    ifs.close();

    return 0;
}

//getline indlæser data fra ifs, til str, indtil den møder ' ' (et mellemrum)
//atoi konverterer en streng (char *) til en integer
//str.c_str() returnerer en char*-repræsentation af str (Som kan bruges i atoi)
Avatar billede mbulow Nybegynder
17. maj 2002 - 10:36 #4
NEVER MIND... Jeg havde lige glemt at ifs >> i allerede selv tager sig af konverteringen... DOH... Sorry
Avatar billede henrik10 Nybegynder
17. maj 2002 - 11:23 #5
Tak for jeres respons.
Maaske har jeg vaeret daarlig til at forklare mig, men jeg skal lave en textfil
hvor jeg skal have foelgende integers: 2  13  48  90  23  44  88  45  97  32 
48  97  67 453.
Jeg proevede at lave det i Notepad, men filen kunne ikke aabnes. Saa mit spoergs-
maal er hvordan jeg laver denne fil. Det er nok et lidt for let spoergsmaal
for mange af jer.
Avatar billede chries Nybegynder
17. maj 2002 - 11:26 #6
åben notepad
tast eller paste tallene ind.
gem som datafile.txt i projekt stien (den kigger efter filen der når du er i visual c++).
og lig den ved exe filen( den kigger i den sti hvor exe filen er når du stater den "manuel")
Avatar billede chries Nybegynder
17. maj 2002 - 11:28 #7
eller bare gem den i c:\
og ændre
#define  DATAFILE "datafile.txt

til
#define  DATAFILE "c:\\datafile.txt
Avatar billede chries Nybegynder
17. maj 2002 - 11:29 #8
glemte afsluttende "
Avatar billede henrik10 Nybegynder
17. maj 2002 - 11:54 #9
Jamen, saa virker det - altsaa med at gemme det i c:\\. Jeg troede ikke at det var noedvendigt.
Tak for hjaelpen det var helt kanon og du faar som fortjent pointene.
Maa jeg spoerge om hvilken uddannelse du har (chries), du har mange gode svar.
Avatar billede chries Nybegynder
17. maj 2002 - 11:57 #10
Står i min mini site ting man har her på eksperten :-)
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester