Chào mừng đến với Diễn đàn lập trình - Cộng đồng lập trình.
Kết quả 1 đến 4 của 4
  1. #1
    Ngày tham gia
    Sep 2015
    Bài viết
    0

    chương trình kiểm tra ISBN


    CS 210 - Program #4

    An ISBN (International Standard Book Number) identifies a unique publication. An ISBN is ten digits. The first nine digits must be decimal digits (0...9). The tenth may a decimal digit or the letter X, according to the checksum, discussed below. Three single dashes may be between any of the characters, but an ISBN must not begin or end with a dash.

    Some example ISBNs:

    0-201-88337-6
    0-13-117334-0
    0821211315 (no dashes ok)
    1-57231-866-X

    The last character of an ISBN number is a checksum. The checksum is the determined by the first 9 digits; it is computed by taking modulo 11 (the remainder after dividing by 11) of the sum of each digit multiplied by its position in the ISBN. The letter X corresponds to a value of 10.

    Here are two ISBNs and the calculations that show how the check sum is determined:

    0-201-88337-6 -> (0*1 + 2*2 + 0*3 + 1*4 + 8*5 + 8*6 + 3*7 + 3*8 + 7*9) mod 11 = 6
    1-57231-866-X -> (1*1 + 5*2 + 7*3 + 2*4 + 3*5 + 1*6 + 8*7 + 6*8 + 6*9) mod 11 = 10 (X)

    For more info, check out:
    www.isbn.org
    www.amazon.com Try a book search by ISBN

    Some invalid ISBNs:

    0-201-8A337-6 (bad digit)
    0-201-88337-63 (too many digits)
    0-201-88-337-6 (too many dashes)
    0-201883376 (not enough dashes)
    0-201-88337-3 (wrong check sum)
    -013-117334-0 (beginning or ending dash)
    157231--866-X (sequential dashes)
    013-1134-0 (too few digits)
    Mã:
    // filename isbn.cpp
    
    
    
    // Program 4 - Validate ISBN numbers program
    // Description: This program asks the user whether he wants to validate
    //				ISBN numbers from his own input or from a file of isbn numbers
    
    // Start program
    
    // Header files
    
    #include <iostream>				// In/Out, standard
    #include <fstream>				// File input/output
    #include <cctype>				// Character testing
    #include <string>				// String
    using namespace std;
    
    // Constant declarations
    
    const char NWLN = '
    ';			// Defines newline in stream
    
    // Function declarations
    
    void instruction();				// Displays instructions
    void userinput(char&);			// Gets user input
    void fileinput(char&);			// Gets file input
    void test(string);				// Tests ISBN numbers
    void convert(char, int&);		// Converts character numbers to int numbers 
    
    // Start of main
    
    int main()
    {
    	int choice;					// User choice value
    	char check;					// Main loop test flag
    
    	// Start of main loop
    	
    	do {						// while check is equal to m
    		instruction();			// Give user instructions
    		
    		// Get user input
    		
    		cout << "Choice: ";
    		cin >> choice;
    		cout << " " << endl;
    
    		// User choice decision switch statment
    		
    		switch(choice)
    		{
    		case 1:                 // Manual input
    			userinput(check);
    			break;
    		case 2:                 // File input
    			fileinput(check);
    			break;
    		case 3:                 //  All done!
    			cout << "Goodbye" << endl;	// Check flag set to end loop
    			check = 'q';
    			break;
    		default: 
    			cerr << "Invalid choice - " << choice << endl
    				<< "enter again please. " << endl << endl;
    		}
    		
    		// End switch
    		
    	} while (check == 'm');
    	
    	// End main loop
    	
    	system("pause");
    	return 0;
    }
    
    // End main
    
    // Instruction subprogram
    
    void instruction()
    {
    	cout << "***** Isbn Number Validator *****" << endl << endl << endl;
    	
    	cout << "| Enter -1- to validate one or more isbn number by typing them in." << endl
    		 << "| Enter -2- to validate a text file of isbn numbers." << endl
    		 << "| Enter -3- to quit." << endl << endl;
    }
    
    // End subprogram
    
    // User input subprogram: Gets user isbn number
    
    void userinput(char& check)
    {
    	string isbn;				// Isbn number
    	
    	cout << "Enter an isbn: "; 
    
    	// !!! error, if i use the getline function instead of just cin
    	// like getline(cin, isbn) or getline(cin, isbn, '
    '),
    	// it wont take isbn numbers and gives 
    	// me an error in the program and according to the book
    	// it should work, because i wanted to use getline here to get an
    	// isbn number with spaces and it won't let me, so i just used cin. !!!!!
    	cin.ignore(80, '
    ');
    	getline(cin, isbn);
    	if (isbn.at(isbn.length() - 1) == '
    ')
    	    isbn.erase(isbn.length() - 1, 1);
    	
    	cout << " " << endl;
    	
    	// Test isbn number main loop
    	
    	while (isbn.at(0) != 'M' && isbn.at(0) != 'm')
    	{
    		system("cls");
    		test(isbn);
    		system("cls");
    		cout << "Enter an isbn or 'M' to return to main menu:";
    		getline(cin, isbn);
    		if (isbn.at(isbn.length() - 1) == '
    ')
    		    isbn.erase(isbn.length() - 1, 1);
    		cout << " " << endl;
    	}
    	
    	// End loop
    	
    	system("cls");
    	check = 'm';
    }
    
    // End subprogram
    
    // File input subprogram: Gets file with isbn numbers
    
    void fileinput(char& check)
    {
    	string file;				// User's Isbn file
    	string isbn;				// Isbn number
    	int num;					// Number of isbn's in file
    	int linecount;				// Line count flag to compare with sum
    	ifstream ins;				// Define input
    	linecount = 0;
    	num = 0;
    	cout << "Enter filename with isbn numbers: ";
    	cin >> file;
    	
    	// Open file
    	
    	ins.open(file.c_str());
    	
    	// File open error test
    	
    	if  (ins.fail())
    	{
    		cerr << "Error - Can't open file [ " << file << " ] for input" << endl;
    		check = 'm';
    	}
    	
    	// End test
    	
    	// Good open of file
    	
    	else
    	{	
    		
    		ins >> num;
    		ins.ignore(100, NWLN);
    		getline(ins, isbn);
    		
    		// Test isbn number main loop
    		
    		while (!ins.eof() && num != linecount)
    		{	
    			system("cls");
    			linecount++;
    			cout << isbn << endl;
    			test(isbn);
    			system("cls");
    			getline(ins, isbn);
    		}
    		
    		// Close input file
    		
    		ins.close();
    		system("cls");
    	}
    	
    	
    	cout << " " << endl;
    	check = 'm';
    	
    	
    }
    
    // End subprogram
    
    // Test subprogram: Tests isbn number
    
    void test(string isbn)
    {
    	int charcount;					// Count of character digits
    	int dashstart;					// Test variable for dash at beginning or end of number
    	int counter;					// Counts characters in string and used in testing
    	int value;						// Value of isbn formula and final value equals remainder of formula
    	int lettercheck;				// Test count variable for letter in isbn
    	int dashcount;					// Test count variable for dashes in isbn
    	int doubledash;					// Test count variable for double dashes in isbn
    	int spacecount;					// Test count variable for spaces in isbn
    	int digit;						// Int value of character digit
    	int length;						// Isbn length
    	char number;					// Character number
    	char prevchar;					// Record last character variable
    	spacecount = 0;
    	lettercheck = 0;
    	value = 0;
    	counter = 1;
    	dashstart = 0;
    	charcount = 0;
    	dashcount = 0;
    	doubledash = 0;
    	
    	length = isbn.length();
    	
    	// Test isbn for loop
    	
    	for(int i=0; i < length - 1; i++)     // for each character
    	{
    		
    		// Check for dash in beginning or end of number
    		
    		if (isbn.at(0) == '-' || isbn.at(length - 1) == '-')
    		{
    			dashstart = 1;
    			counter++;
    		}
    		
    		// Calculate value if isbn has right amount of numbers
    		
    		if ((isdigit(isbn.at(i))) &&
    			(charcount < 9) &&
    			(lettercheck == 0) && isbn.at(i) != '-' && isbn.at(i) != ' ')
    		{
    			number = isbn.at(i);
    			convert(number, digit);
    			value = value + (digit * (counter));
    			counter++;
    			charcount++;
    		}
    		
    		// If isbn has a dash, adds 1 to dashcount
    		
    		if (isbn.at(i) == '-' && dashstart != 1)
    		{
    			dashcount++;
    
    			// Check for double dash
    			
    			if (prevchar == '-')
    				doubledash++;
    			else
    				;
    		}
    		
    		// Check for letter
    		
    		if (isbn.at(i) != '-' && !isdigit(isbn.at(i)) && isbn.at(i) != ' ' && (isbn.at(length - 1) != 'x' || isbn.at(length - 1) != 'X'))
    		{	
    			lettercheck = 1;
    		}
    		
    		// Check for spaces
    		
    		if (isbn.at(i) == ' ')
    		{
    			spacecount++;
    		}
    		
    		
    		// Set previous character variable to last character tested
    		
    		prevchar = isbn.at(i);
    
    	}       // end for each character
    	
    	// End loop
    	
    	
    	// If there isn't a dash at beginning or end of number convert
    	
    	if(dashstart != 1)
    	{
    		
    		// Calculate remainder of forumla
    		
    		value = value % 11;
    		
    		// reminder value statements
    
    		cout << "ISBN: " << isbn << endl << endl;
    		cout << "calculated checksum == " << value << endl << endl;
    	
    
    		if (length == 13 && lettercheck == 0 && charcount == 9 && dashstart == 0)
    		{
    			charcount += 1;
    			number = isbn.at(12);
    		}
    		else if (length == 10 && lettercheck == 0 && charcount == 9 && dashstart == 0)
    		{
    			charcount += 1;
    			number = isbn.at(9);
    		}
    		else if (dashstart == 1 && charcount == 9 && (i > 9 && i < 12))
    		{
    			number = isbn.at(length -1);
    		}
    		else if (dashstart == 1 && charcount == 9 && i > 12)
    		{
    			number = isbn.at(length -1);
    		}
    		else
    		{
    			cout << "Invalid Isbn - will not calculate checksum, return 1" << endl;
    			number = '1';
    		}
    		// Convert last character digit in isbn to int digit to compare to value
    		
    		convert(number, digit);
    	
    	}
    	// Answer output statements based on data
    	
    	if (charcount < 10)
    		cout << " (Not enough digits)" << endl;
    	if (charcount > 10)
    		cout << " (To many digits)" << endl;
    	if (charcount  <  10 && lettercheck == 1)
    		cout << " (Can't have any character except for 'X' at end unless 10 is the remainder)" << endl;
    	if (dashcount > 4)
    		cout << " (Too many dashes)" << endl;
    	if ((dashcount < 3 && dashcount > 0) && length > 10) 
    		cout << " (Not enough dashes)" << endl;
    	if (value != digit)
    		cout << " (Wrong check sum)" << endl;
    	if (dashstart == 1)
    		cout << " (Beginning or ending dash)" << endl;
    	if (doubledash > 0)
    		cout << " (Sequential dashes)" << endl;
    	if (spacecount > 4)
    		cout << " (Too many spaces)" << endl;
    	if ((spacecount < 3 && spacecount > 0) && length > 10)
    		cout << " (Not enough spaces)" << endl;
    	if ((spacecount == 0 || spacecount == 3) && (dashcount == 3 || dashcount == 0) && (charcount == 10) && (counter == 10) && (digit == value))
    		cout << " (Good number and checksum)" << endl;
    	else
    		;
    	
    	cout << " " << endl;
    	system("pause");
    
    }   // end test function
    
    // End subprogram
    
    // Convert subprogram: Converts character digits to int digits
    
    void convert(char number, int& digit)
    {
    	if (number == 'x' || number == 'X')
    		digit = 10;
    	else
    		digit = int(number) - int('0');
    }
    
    // End subprogram
    
    // End program
    tình hình là chương trình vẫn chưa complie ,mong anh em giúp mình cho nó cha.y dùm, email cho pro Huy Nguyen nhung weekend mớii đươc nhưng mình cần nó gấp lấm

  2. #2
    - Tui giúp cậu lần này thôi đó, code cậu viết fragile quá, không bao giờ handle quá nhiều tasks trong 1 hàm.
    - Cậu đang học Uni nào vậy ? Bài này trong cuốn Starting Out C++ phải không, tui thấy quen lắm nhưng không chắc vì sách đó tui bán lại mùa trước rùi.
    - Tui làm đơn giản nhất rùi đó, nếu dùng full STL và function object code sẽ more elegant. À con trỏ hàm cũng ok [IMG]images/smilies/wink.png[/IMG]. Trường hợp space thì cậu tự mà thêm vào nhé [IMG]images/smilies/wink.png[/IMG] !

    Mã:
    // filename isbn.cpp#include <iostream>             // In/Out, standard#include <fstream>              // File input/output#include <cctype>               // Character testing#include <string>               // String using namespace std; const int MAX_ERRORS          = 9;const int MAX_DASHES          = 3;const int MAX_DIGITS          = 10; enum ErrorType{    BEGIN_OR_END_BY_DASH,     // 1    WRONG_END_DIGIT,          // 2    SEQUENTIAL_DASHES,        // 3    DASHES_BAD_POSITION,      // 4    NOT_ENOUGH_DIGITS,        // 5    TOO_MANY_DIGITS,          // 6    NOT_ENOUGH_DASHES,        // 7    TOO_MANY_DASHES,          // 8    WRONG_CHECK_SUM,          // 9    OK_BUT_NOT_WELL_FORM,     // 10    VALID_AND_WELL_FORM       // 11}; enum UserOption{    MANUAL_INPUT,    FILE_INPUT,    QUIT,    INVALID_CHOICE};  bool       open_input_file( const string& file_name );UserOption get_user_choice();void       print_instruction();string     read_isbn_number( istream& in );bool       open_input_file( ifstream& inf );bool       is_begin_end_dash( const string& isbn );bool       is_last_digit_invalid( const string& isbn );int        count_dashes( const string& isbn );int        count_digits( const string& isbn );bool       is_sequential_dashes( const string& isbn );bool       is_dashes_at_bad_position( const string& isbn );int        get_check_sum( const string& isbn );void       test_isbn( const string& isbn );void       print_error_type_messages( ErrorType er );int        convert_single_char_to_int( char number );bool       continue_or_quit( const char* mess ); int main(){    int        choice;                  // User choice value    UserOption usop;    string     isbn_number;    ifstream   inf;    char       retest;     do {        print_instruction();        usop = get_user_choice();         cin.ignore( 80, '
    ' );         switch( usop )        {            case MANUAL_INPUT :            {                cout << "Enter an isbn : ";                isbn_number = read_isbn_number( cin );                break;            }            case FILE_INPUT :            {                if( open_input_file( inf ) )                    isbn_number = read_isbn_number( inf );                else                    cout << endl;                break;            }            case QUIT :            {                cout << "
    ... About to Exit " << endl;                break;            }            default :            {                cerr << "
    ... Invalid choice " << choice << endl;                break;            }        }         if( !isbn_number.empty() )        {            test_isbn( isbn_number );        }         cout << "
     Hit the enter key to continue....";        cin.ignore( 80, '
    ' );         if( usop == FILE_INPUT )            inf.clear();     } while( continue_or_quit( "
     Continue ( Y or N ) ?" ) );     return 0;} void print_instruction(){    cout << "***** Isbn Number Validator *****" << endl << endl << endl;    cout << "| Enter -1- to validate one or more isbn number by typing them in." << endl         << "| Enter -2- to validate a text file of isbn numbers." << endl         << "| Enter -3- to quit." << endl << endl;} UserOption get_user_choice(){    int        choice;    UserOption usop;     cout << "Choice: ";    cin >> choice;    cout << " " << endl;     switch( choice )    {    case 1 :            usop = MANUAL_INPUT;            break;    case 2 :            usop = FILE_INPUT;            break;    case 3 :            usop = QUIT;            break;    default :            usop = INVALID_CHOICE;            break;    }    return usop;}  string read_isbn_number( istream& in ){    string isbn_number;    getline( in, isbn_number );    return isbn_number;} bool open_input_file( ifstream& inf ){    string   file_name;    cout << "Enter input file : 
    ";    cin >> file_name;     inf.open( file_name.c_str() );    if ( inf.fail() )    {        cerr << "Error - Can't open file [ " << file_name << " ] for input" << endl;        return false;    }    else    {        cout << "Success - Open file [ " << file_name << " ] for input. " << endl;        return true;    }} bool is_begin_end_dash( const string& isbn ){    if( isbn.at( 0 ) == '-' || isbn.at( isbn.length() - 1 ) == '-' )        return true;    return false;} bool is_last_digit_invalid( const string& isbn ){    char last_char = isbn.at( isbn.length() - 1 );    if( last_char != 'x' && last_char != 'X' && !isdigit( last_char ) )        return true;    return false;} int count_dashes( const string& isbn ){    int len    = isbn.length();    int dashes = 0;    for( int i = 0; i < len; ++i )    {        if( isbn.at( i ) == '-' )            dashes++;    }    return dashes;} int count_digits( const string& isbn ){    int len    = isbn.length();    int digits = 0;    for( int i = 0; i < len; ++i )    {        if( isdigit( isbn.at( i ) ) )            digits++;    }    return digits;} bool is_sequential_dashes( const string& isbn ){    int len    = isbn.length();    for( int i = 0; i < len - 1; ++i )    {        if( isbn.at( i ) == '-' && isbn.at( i + 1 ) == '-' )            return true;    }    return false;} bool is_dashes_at_bad_position( const string& isbn ){    if(        isbn.at( 1 )  != '-' ||        isbn.at( 5 )  != '-' ||        isbn.at( 11 ) != '-'    )        return true;    return false;} int get_check_sum( const string& isbn ){    int len = isbn.length();    int sum = 0;    int cnt = 1;    for( int i = 0; i < len - 1; ++i )    {        if( isdigit( isbn.at( i ) ) )        {            sum += cnt * convert_single_char_to_int( isbn.at( i ) );            cnt++;        }    }    return sum;}   void test_isbn( const string& isbn ){    ErrorType er;    int       number_digits = count_digits( isbn );    int       number_dashes = count_dashes( isbn );     if( is_begin_end_dash( isbn ) )    {        er = BEGIN_OR_END_BY_DASH;    }    else if( is_last_digit_invalid( isbn ) )    {        er = WRONG_END_DIGIT;    }    else if( is_sequential_dashes( isbn ) )    {        er = SEQUENTIAL_DASHES;    }    else if( number_digits != MAX_DIGITS )    {        if( number_digits < MAX_DIGITS )            er = NOT_ENOUGH_DIGITS;        else            er = TOO_MANY_DIGITS;    }    else if( number_dashes == MAX_DASHES || number_dashes == 0 )    {        if( number_dashes == MAX_DASHES && is_dashes_at_bad_position( isbn ) )        {            er = DASHES_BAD_POSITION;        }        else        {            int check_sum  = get_check_sum( isbn );            int last_digit = convert_single_char_to_int( isbn.at( isbn.length() - 1 ) );             if( ( check_sum % ( MAX_DIGITS + 1 ) ) == last_digit )            {                if( number_dashes == 0 )                    er = OK_BUT_NOT_WELL_FORM;                else                    er = VALID_AND_WELL_FORM;            }            else            {                er = WRONG_CHECK_SUM;            }        }    }    else    {        if( number_dashes > MAX_DASHES )            er = TOO_MANY_DASHES;        else            er = NOT_ENOUGH_DASHES;    }     print_error_type_messages( er );}   void print_error_type_messages( ErrorType er ){    switch( er )    {    case WRONG_END_DIGIT :        cout << " (Can't have any character except for 'X' at end unless 10 is the remainder)" << endl;        break;    case NOT_ENOUGH_DIGITS :        cout << " (Not enough digits)" << endl;        break;    case TOO_MANY_DIGITS :        cout << " (To many digits)" << endl;        break;    case NOT_ENOUGH_DASHES :        cout << " (Not enough dashes)" << endl;        break;    case TOO_MANY_DASHES :        cout << " (Too many dashes)" << endl;        break;    case WRONG_CHECK_SUM :        cout << " (Wrong check sum)" << endl;        break;    case BEGIN_OR_END_BY_DASH :        cout << " (Beginning or ending dash)" << endl;        break;    case SEQUENTIAL_DASHES :        cout << " (Sequential dashes)" << endl;        break;    case DASHES_BAD_POSITION :        cout << " (Dashes at wrong places)" << endl;        break;    case OK_BUT_NOT_WELL_FORM :        cout << " (Good number but not well-formed) " << endl;        break;    default :        cout << " (Good number and well-formed)" << endl;    }} int convert_single_char_to_int( char number ){    if( number == 'x' || number == 'X' )        return 10;    else        return static_cast< int >( number ) - static_cast< int >( '0' );} bool continue_or_quit( const char* mess ){    cout << mess << "
    ";    string repl;    while( 1 )    {        cin >> repl;        if( repl.at( 0 ) == 'Y' || repl.at( 0 ) == 'y' )            return true;        else if( repl.at( 0 ) == 'N' || repl.at( 0 ) == 'n' )            return false;        else            cout << "
     Invalid answer. Try again !
    ";    }}

  3. #3
    Mã:
    // filename = isbn.cpp
    
    // Prof. Gelotte
    
    // Program 4 - Validate ISBN numbers program
    // Description: This program asks the user whether he wants to validate
    //				ISBN numbers from his own input or from a file of isbn numbers
    
    // Start program
    
    // Header files
    
    #include <iostream>				// In/Out, standard
    #include <fstream>				// File input/output
    #include <cctype>				// Character testing
    #include <string>				// String
    using namespace std;
    
    // Constant declarations
    
    const char NWLN = '
    ';			// Defines newline in stream
    
    // Function declarations
    
    void instruction();				// Displays instructions
    void userinput(char&);			// Gets user input
    void fileinput(char&);			// Gets file input
    void test(string);				// Tests ISBN numbers
    void convert(char, int&);		// Converts character numbers to int numbers 
    
    // Start of main
    
    int main()
    {
    	char choice;					// User choice value
    	char check = 'm';					// Main loop test flag
    
    	// Start of main loop
    	
    	do {						// while check is equal to m
    		instruction();			// Give user instructions
    		
    		// Get user input
    		
    		cout << "Choice: ";
    		cin >> choice;
    		cout << " " << endl;
    
    		// User choice decision switch statment
    		
    		switch(choice)
    		{
    		case '1':                 // Manual input
    			userinput(check);
    			break;
    		case '2':                 // File input
    			fileinput(check);
    			break;
    		case '3':                 //  All done!
    			cout << "Goodbye" << endl;	// Check flag set to end loop
    			check = 'q';
    			break;
    		default:
    			cerr << "Invalid choice - " << choice << endl
    				<< "enter again please. " << endl << endl;
    		}
    
    		// End switch
    
    	} while (check == 'm');
    	
    	// End main loop
    	
    	system("pause");
    	return 0;
    }
    
    // End main
    
    // Instruction subprogram
    
    void instruction()
    {
    	cout << "***** Isbn Number Validator *****" << endl << endl << endl;
    	
    	cout << "| Enter -1- to validate one or more isbn number by typing them in." << endl
    		 << "| Enter -2- to validate a text file of isbn numbers." << endl
    		 << "| Enter -3- to quit." << endl << endl;
    }
    
    // End subprogram
    
    // User input subprogram: Gets user isbn number
    
    void userinput(char& check)
    {
    	string isbn;				// Isbn number
    	
    	cout << "Enter an isbn: "; 
    
    	// !!! error, if i use the getline function instead of just cin
    	// like getline(cin, isbn) or getline(cin, isbn, '
    '),
    	// it wont take isbn numbers and gives 
    	// me an error in the program and according to the book
    	// it should work, because i wanted to use getline here to get an
    	// isbn number with spaces and it won't let me, so i just used cin. !!!!!
    	cin.ignore(80, '
    ');
    	getline(cin, isbn);
    	if (isbn.at(isbn.length() - 1) == '
    ')
    	    isbn.erase(isbn.length() - 1, 1);
    	
    	cout << " " << endl;
    	
    	// Test isbn number main loop
    	
    	while (isbn.at(0) != 'M' && isbn.at(0) != 'm')
    	{
    		system("cls");
    		test(isbn);
    		system("cls");
    		cout << "Enter an isbn or 'M' to return to main menu:";
    		getline(cin, isbn);
    		if (isbn.at(isbn.length() - 1) == '
    ')
    		    isbn.erase(isbn.length() - 1, 1);
    		cout << " " << endl;
    	}
    	
    	// End loop
    	
    	system("cls");
    	check = 'm';
    }
    
    // End subprogram
    
    // File input subprogram: Gets file with isbn numbers
    
    void fileinput(char& check)
    {
    	string file;				// User's Isbn file
    	string isbn;				// Isbn number
    	int num;					// Number of isbn's in file
    	int linecount;				// Line count flag to compare with sum
    	ifstream ins;				// Define input
    	linecount = 0;
    	num = 0;
    	cout << "Enter filename with isbn numbers: ";
    	cin >> file;
    	
    	// Open file
    	
    	ins.open(file.c_str());
    	
    	// File open error test
    	
    	if  (ins.fail())
    	{
    		cerr << "Error - Can't open file [ " << file << " ] for input" << endl;
    		check = 'm';
    	}
    	
    	// End test
    	
    	// Good open of file
    	
    	else    // else WHAT>?@#$(*&@#$()*#$&()*!!!
    	{	
    		
    		ins >> num;
    		ins.ignore(100, NWLN);
    		getline(ins, isbn);
    		
    		// Test isbn number main loop
    		
    		while (!ins.eof() && num != linecount)
    		{	
    			system("cls");
    			linecount++;
    			cout << isbn << endl;
    			test(isbn);
    			system("cls");
    			getline(ins, isbn);
    		}
    		
    		// Close input file
    		
    		ins.close();
    		system("cls");
    	}   // end WHAT?!@#*&^#$@(*&$#^(&*!!
    	
    	
    	cout << " " << endl;
    	check = 'm';
    	
    	
    }    // end what?
    
    // End subprogram
    
    // Test subprogram: Tests isbn number
    
    void test(string isbn)
    {
    	int charcount;					// Count of character digits
    	int dashstart;					// Test variable for dash at beginning or end of number
    	int counter;					// Counts characters in string and used in testing
    	int value;						// Value of isbn formula and final value equals remainder of formula
    	int lettercheck;				// Test count variable for letter in isbn
    	int dashcount;					// Test count variable for dashes in isbn
    	int doubledash;					// Test count variable for double dashes in isbn
    	int spacecount;					// Test count variable for spaces in isbn
    	int digit;						// Int value of character digit
    	int length;						// Isbn length
    	char number;					// Character number
    	char prevchar;					// Record last character variable
    	spacecount = 0;
    	lettercheck = 0;
    	value = 0;
    	counter = 1;
    	dashstart = 0;
    	charcount = 0;
    	dashcount = 0;
    	doubledash = 0;
    	
    	length = isbn.length();
    	
    	// Test isbn for loop
    	
    	for(int i=0; i < length - 1; i++)     // for each character
    	{
    		
    		// Check for dash in beginning or end of number
    		
    		if (isbn.at(0) == '-' || isbn.at(length - 1) == '-')
    		{
    			dashstart = 1;
    			counter++;
    		}
    		
    		// Calculate value if isbn has right amount of numbers
    		
    		if ((isdigit(isbn.at(i))) &&
    			(charcount < 9) &&
    			(lettercheck == 0) && isbn.at(i) != '-' && isbn.at(i) != ' ')
    		{
    			number = isbn.at(i);
    			convert(number, digit);
    			value = value + (digit * (counter));
    			counter++;
    			charcount++;
    		}
    		
    		// If isbn has a dash, adds 1 to dashcount
    		
    		if (isbn.at(i) == '-' && dashstart != 1)
    		{
    			dashcount++;
    
    			// Check for double dash
    			
    			if (prevchar == '-')
    				doubledash++;
    			else
    				;
    		}
    		
    		// Check for letter
    		
    		if (isbn.at(i) != '-' && !isdigit(isbn.at(i)) && isbn.at(i) != ' ' && (isbn.at(length - 1) != 'x' || isbn.at(length - 1) != 'X'))
    		{	
    			lettercheck = 1;
    		}
    		
    		// Check for spaces
    		
    		if (isbn.at(i) == ' ')
    		{
    			spacecount++;
    		}
    		
    		
    		// Set previous character variable to last character tested
    		
    		prevchar = isbn.at(i);
    
    	}       // end for each character
    	
    	// End loop
    	
    	
    	// If there isn't a dash at beginning or end of number convert
    	int i;
    	if(dashstart != 1)
    	{
    		
    		// Calculate remainder of forumla
    		
    		value = value % 11;
    		
    		// reminder value statements
    
    		cout << "ISBN: " << isbn << endl << endl;
    		cout << "calculated checksum == " << value << endl << endl;
    	
    
    		if (length == 13 && lettercheck == 0 && charcount == 9 && dashstart == 0)
    		{
    			charcount += 1;
    			number = isbn.at(12);
    		}
    		else if (length == 10 && lettercheck == 0 && charcount == 9 && dashstart == 0)
    		{
    			charcount += 1;
    			number = isbn.at(9);
    		}
    		else if (dashstart == 1 && charcount == 9 && (i > 9 && i < 12))
    		{
    			number = isbn.at(length -1);
    		}
    		else if (dashstart == 1 && charcount == 9 && i > 12)
    		{
    			number = isbn.at(length -1);
    		}
    		else
    		{
    			cout << "Invalid Isbn - will not calculate checksum, return 1" << endl;
    			number = '1';
    		}
    		// Convert last character digit in isbn to int digit to compare to value
    		
    		convert(number, digit);
    	
    	}
    	// Answer output statements based on data
    	
    	if (charcount < 10)
    		cout << " (Not enough digits)" << endl;
    	if (charcount > 10)
    		cout << " (To many digits)" << endl;
    	if (charcount  <  10 && lettercheck == 1)
    		cout << " (Can't have any character except for 'X' at end unless 10 is the remainder)" << endl;
    	if (dashcount > 4)
    		cout << " (Too many dashes)" << endl;
    	if ((dashcount < 3 && dashcount > 0) && length > 10) 
    		cout << " (Not enough dashes)" << endl;
    	if (value != digit)
    		cout << " (Wrong check sum)" << endl;
    	if (dashstart == 1)
    		cout << " (Beginning or ending dash)" << endl;
    	if (doubledash > 0)
    		cout << " (Sequential dashes)" << endl;
    	if (spacecount > 4)
    		cout << " (Too many spaces)" << endl;
    	if ((spacecount < 3 && spacecount > 0) && length > 10)
    		cout << " (Not enough spaces)" << endl;
    	if ((spacecount == 0 || spacecount == 3) && (dashcount == 3 || dashcount == 0) && (charcount == 10) && (counter == 10) && (digit == value))
    		cout << " (Good number and checksum)" << endl;
    	else
    		;
    	
    	cout << " " << endl;
    	system("pause");
    
    }   // end test function
    
    // End subprogram
    
    // Convert subprogram: Converts character digits to int digits
    
    void convert(char number, int& digit)
    {
    	if (number == 'x' || number == 'X')
    		digit = 10;
    	else
    		digit = int(number) - int('0');
    }
    
    // End subprogram
    
    // End program
    thanks pro morock nhiều lắm, mình tự làm được rồi nè, pro có góp ý gì thêm cho mình hông, mình mới học programming được 5 tuần thôi, mình đang ở Us, người ta bắt đọc nhiều lắm, nhớ không hết luôn, diễn đàn này thiệ bổ ích

  4. #4
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    - Tui nhìn code thì biết chắc cậu không học ở VN [IMG]images/smilies/biggrin.png[/IMG] ! Mà cậu học ở trường nào thế ? Biết đâu chung trường của nên [IMG]images/smilies/biggrin.png[/IMG] !
    - Học 5 tuần mà viết thế là tốt lắm rồi đây [IMG]images/smilies/wink.png[/IMG] !
    - Còn bài cậu thì có nhiều chỗ để bàn :
    1. Enum dùng sẽ sáng nghĩ hơn.
    2. Hai cái hàm fileinput & userinput có nhiều điểm giống( có thể dùng istream& cho ifstream và cin ). Nhưng code cậu implement khác nhau, dư nhiều code không cần thiết.
    3. Cậu nên nhớ là không bao giờ cho input và output vào các function khác.
    Ví dụ đoạn :

    Mã:
    if (charcount < 10)        cout << " (Not enough digits)" << endl;    if (charcount > 10)        cout << " (To many digits)" << endl;    if (charcount  <  10 && lettercheck == 1)        cout << " (Can't have any character except for 'X' at end unless 10 is the remainder)" << endl;    if (dashcount > 4)        cout << " (Too many dashes)" << endl;    if ((dashcount < 3 && dashcount > 0) && length > 10)         cout << " (Not enough dashes)" << endl;    if (value != digit)        cout << " (Wrong check sum)" << endl;    if (dashstart == 1)        cout << " (Beginning or ending dash)" << endl;    if (doubledash > 0)        cout << " (Sequential dashes)" << endl;    if (spacecount > 4)        cout << " (Too many spaces)" << endl;    if ((spacecount < 3 && spacecount > 0) && length > 10)        cout << " (Not enough spaces)" << endl;    if ((spacecount == 0 || spacecount == 3) && (dashcount == 3 || dashcount == 0) && (charcount == 10) && (counter == 10) && (digit == value))        cout << " (Good number and checksum)" << endl;    else        ;
    Giả nếu tui cần chuyển sang tiếng Việt thì cậu nghĩ có bao nhiêu hàm cậu cần phải sữa lại ?
    3. Hàm test( string& ) phải là test( const string& ) vì cậu chỉ test chứ không modify string.
    4. Test 1 chức năng 1 hàm thì sẽ dễ hơn RẤT RẤT nhiều vì sao ? Vì khi cậu muốn thêm hay bớt cậu không test toàn bộ. Hàm test là quá dài, 1 cái sai thì cá đảm kia chạy bằng niềm tin. Thà cậu paid-off cho function hơn là cậu gom 1 đống vào.
    ->
    5. Khi tui học lớp này, cô tui chấm rất kĩ : chú ý thêm các chỗ thiếu const, và gom những cái chung để ra ngoài. Không để magic number nhiều quá, dùng const int để khai báo nó với 1 cái tên có ý nghĩa hơn. Hàm cách 2 blank line. Main đặt trên đầu, nhớ ghi tên đầy đủ và giới thiệt sơ chương trình trong phần output.
    6. Lần sau không post vào box project( đây là nơi chia sẽ mã nguồn ), không phải nơi hỏi ! Dù cậu xài Visual C++ ở trường nhưng cái này là C++ not Visual C++, chú ý post đúng box.
    ps : có mod nào move dùm vào box C++ được không ?

 

 

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •