示例#1
0
extern "C" JNIEXPORT jstring JNICALL
Java_java_util_Date_toString(JNIEnv* e, jclass c UNUSED, jlong when)
{
  const unsigned BufferSize UNUSED = 27;

  time_t time = when / 1000;

#ifdef PLATFORM_WINDOWS
  e->MonitorEnter(c);
#  ifdef _MSC_VER
  char buffer[BufferSize];
  ctime_s(buffer, BufferSize, &time);
  removeNewline(buffer);
#  else
  char* buffer = ctime(&time);
#  endif
  jstring r = e->NewStringUTF(buffer);
  e->MonitorExit(c);
  return r;
#else
  char buffer[BufferSize];
  ctime_r(&time, buffer);
  removeNewline(buffer);
  return e->NewStringUTF(buffer);
#endif
}
示例#2
0
文件: smallsh.c 项目: MJ21/CSProjects
int main(int argc, char **argv[])
{
	while(1)
	{
		
		struct Status exitstatus, *pstatus;
		pstatus = &exitstatus;
		char *arg[520];
		char line[520];
		int numArgs;
		int exitnum;
		pid_t pid;
		int backstatus, i;
		
		pid = waitpid(-1, &backstatus, WNOHANG); 
		if(pid > 0)
		{
			printf("background pid %d is done: ", pid);
			if (WIFEXITED(backstatus))
			{
				exitstatus.type = "exit";
				exitstatus.statusNum = backstatus;
				printf("Exit value %d\n", backstatus);
			}
			else if (WIFSIGNALED(backstatus))
			{
				exitstatus.type = "signal";
				exitstatus.statusNum = backstatus;
				printf("terminated by signal %d\n", backstatus);
			} 
		}	
		
		//Command prompt for new commands
		printf(": ");
		fflush(stdout);
		
		//Receive commands from the standard input
		fgets(line, 520, stdin);
		
		if(feof(stdin))
		{
			exit(1);
		}
		removeNewline(line, 520);
		
		//*****Call Parsing function to parse commands into an array of strings****
		numArgs = parseArgs(line, arg);
		
		if(arg[0] == NULL)
		{
			continue;
		}
		
		exitnum = execute_builtin(arg, numArgs, pstatus);

		memset(arg, 0, 520);
		
	}
	return EXIT_SUCCESS;
}
示例#3
0
void openDictionary(void){
	FILE *dict = fopen("dict.txt", "r");
	int i = 0;
	while (fgets(acceptable[i], MAXLENGTH, dict)){
		removeNewline(acceptable[i++]);
		nameCount++;
	}
	fclose(dict);
}
示例#4
0
int main ( void ){


  char *myString = malloc(sizeof(char) * MAX_LINE);

  printf("\nPlease enter a string: ");
  fgets(myString, MAX_LINE - 1, stdin);
  myString = removeNewline(myString);

  printf("\nReverse the following string:\n%s\n", myString);

  myString = reverseWords(myString);


  printf("The string with the words reversed is:\n%s\n", myString);

  free(myString);

  printf("\n\n\n");

  return 0;
}
int main(void)
{
	char naturalInput[256];
	int naturalLength;
		
		while(1)
		{
			printf("Input a natural number in decimal representation.\n");
			printf(">");
			
			fgets(naturalInput, 256, stdin);
			
			removeNewline(naturalInput);	//Remove newline character from array.
			
			naturalLength = strlen(naturalInput);
			
			if(isValidNumber(naturalInput, naturalLength) == 1)	//Check if array contains non-digits.
				outputBinary(naturalInput);
			else
				printf("\nPlease input a natural number in decimal representation.\n");
		}
		
	return 0;
}
示例#6
0
IOStatus KGrGameIO::fetchGameListData
        (const Owner o, const QString & dir, QList<KGrGameData *> & gameList,
                              QString & filePath)
{
    QDir directory (dir);
    QStringList pattern;
    pattern << "game_*";
    QStringList files = directory.entryList (pattern, QDir::Files, QDir::Name);

    // KGr 3 has a game's data and all its levels in one file.
    // KGr 2 has all game-data in "games.dat" and each level in a separate file.
    bool kgr3Format = (files.count() > 0);
    if (! kgr3Format) {
        files << "games.dat";
    }

    // Loop to read each file containing game-data.
    foreach (const QString &filename, files) {
        if (filename == "game_ende.txt") {
            continue;			// Skip the "ENDE" file.
        }

        filePath = dir + filename;
        KGrGameData * g = initGameData (o);
        gameList.append (g);
        // kDebug()<< "GAME PATH:" << filePath;

        openFile.setFileName (filePath);

        // Check that the game-file exists.
        if (! openFile.exists()) {
            return (NotFound);
        }

        // Open the file for read-only.
        if (! openFile.open (QIODevice::ReadOnly)) {
            return (NoRead);
        }

        char c;
        QByteArray textLine;
        QByteArray gameName;

        // Find the first line of game-data.
        c = getALine (kgr3Format, textLine);
        if (kgr3Format) {
            while ((c != 'G') && (c != '\0')) {
                c = getALine (kgr3Format, textLine);
            }
        }
        if (c == '\0') {
            openFile.close();
            return (UnexpectedEOF);	// We reached end-of-file unexpectedly.
        }

        // Loop to extract the game-data for each game on the file.
        while (c != '\0') {
            if (kgr3Format && (c == 'L')) {
                break;			// End of KGr 3 game-file header.
            }
            // Decode line 1 of the game-data.
            QList<QByteArray> fields = textLine.split (' ');
            g->nLevels = fields.at (0).toInt();
            g->rules   = fields.at (1).at (0);
            g->prefix  = fields.at (2);
            // kDebug() << "Levels:" << g->nLevels << "Rules:" << g->rules <<
                // "Prefix:" << g->prefix;

            if (kgr3Format) {
                // KGr 3 Format: get skill, get game-name from a later line.
                g->skill = fields.at (3).at (0);
            }
            else {
                // KGr 2 Format: get game-name from end of line 1.
                int n = 0;
                // Skip the first 3 fields and extract the rest of the line.
                n = textLine.indexOf (' ', n) + 1;
                n = textLine.indexOf (' ', n) + 1;
                n = textLine.indexOf (' ', n) + 1;
                gameName = removeNewline (textLine.right (textLine.size() - n));
                g->name  = i18n (gameName.constData());
            }

            // Check for further settings in this game.
            // bool usedDwfOpt = false;		// For debug.
            while ((c = getALine (kgr3Format, textLine)) == '.') {
                if (textLine.startsWith ("dwf ")) {
                    // Dig while falling is allowed in this game, or not.
                    g->digWhileFalling = textLine.endsWith (" false\n") ?
                                         false : true;
                    // usedDwfOpt = true;		// For debug.
                }
            }

            if (kgr3Format && (c == ' ')) {
                gameName = removeNewline (textLine);
                g->name  = i18n (gameName.constData());
                c = getALine (kgr3Format, textLine);
            }
            // qDebug() << "Dig while falling" << g->digWhileFalling
                     // << "usedDwfOpt" << usedDwfOpt << "Game" << g->name;
            // kDebug() << "Skill:" << g->skill << "Name:" << g->name;

            // Loop to accumulate lines of about-data.  If kgr3Format, exit on
            // EOF or 'L' line.  If not kgr3Format, exit on EOF or numeric line.
            while (c != '\0') {
                if ((c == '\0') ||
                    (kgr3Format && (c == 'L')) ||
                    ((! kgr3Format) &&
                    (textLine.at (0) >= '0') && (textLine.at (0) <= '9'))) {
                    break;
                }
                g->about.append (textLine);
                c = getALine (kgr3Format, textLine);
            }
            g->about = removeNewline (g->about);	// Remove final '\n'.
            // kDebug() << "Info about: [" + g->about + "]";

            if ((! kgr3Format) && (c != '\0')) {
                filePath = dir + filename;
                g = initGameData (o);
                gameList.append (g);
            }
        } // END: game-data loop

        openFile.close();

    } // END: filename loop

    return (OK);
}
示例#7
0
IOStatus KGrGameIO::fetchLevelData
        (const QString & dir, const QString & prefix,
                const int level, KGrLevelData & d, QString & filePath)
{
    filePath = getFilePath (dir, prefix, level);
    d.level  = level;		// Level number.
    d.width  = FIELDWIDTH;	// Default width of layout grid (28 cells).
    d.height = FIELDHEIGHT;	// Default height of layout grid (20 cells).
    d.layout = "";		// Codes for the level layout (mandatory).
    d.name   = "";		// Level name (optional).
    d.hint   = "";		// Level hint (optional).

    // kDebug()<< "LEVEL PATH:" << filePath;
    openFile.setFileName (filePath);

    // Check that the level-file exists.
    if (! openFile.exists()) {
        return (NotFound);
    }

    // Open the file for read-only.
    if (! openFile.open (QIODevice::ReadOnly)) {
        return (NoRead);
    }

    char c;
    QByteArray textLine;
    IOStatus result = UnexpectedEOF;

    // Determine whether the file is in KGoldrunner v3 or v2 format.
    bool kgr3Format = (filePath.endsWith (".txt"));

    if (kgr3Format) {
        // In KGr 3 format, if a line starts with 'L', check the number.
        while ((c = getALine (kgr3Format, textLine)) != '\0') {
            if ((c == 'L') && (textLine.left (3).toInt() == level)) {
                break;			// We have found the required level.
            }
        }
        if (c == '\0') {
            openFile.close();		// We reached end-of-file.
            return (UnexpectedEOF);
        }
    }  

    // Check for further settings in this level.
    while ((c = getALine (kgr3Format, textLine)) == '.') {
        if (textLine.startsWith ("dwf ")) {
            // Dig while falling is allowed in this level, or not.
            d.digWhileFalling = textLine.endsWith (" false\n") ? false : true;
        }
    }

    // Get the character-codes for the level layout.
    if (c  == ' ') {
        result = OK;
        d.layout = removeNewline (textLine);		// Remove '\n'.

        // Look for a line containing a level name (optional).
        if ((c = getALine (kgr3Format, textLine)) == ' ') {
            d.name = removeNewline (textLine);		// Remove '\n'.

            // Look for one or more lines containing a hint (optional).
            while ((c = getALine (kgr3Format, textLine)) == ' ') {
                d.hint.append (textLine);
            }
            d.hint = removeNewline (d.hint);		// Remove final '\n'.
        }
    }

    // kDebug() << "Level:" << level << "Layout length:" << d.layout.size();
    // kDebug() << "Name:" << "[" + d.name + "]";
    // kDebug() << "Hint:" << "[" + d.hint + "]";

    openFile.close();
    return (result);
}
示例#8
0
//! Execute catalog_pruner.
void executeCatalogPruner( const rapidjson::Document& config )
{
    // Verify config parameters. Exception is thrown if any of the parameters are missing.
    const CatalogPrunerInput input = checkCatalogPrunerInput( config );

    std::cout << std::endl;
    std::cout << "******************************************************************" << std::endl;
    std::cout << "                              Parser                              " << std::endl;
    std::cout << "******************************************************************" << std::endl;
    std::cout << std::endl;

    // Parse catalog and store TLE objects.
    std::ifstream catalogFile( input.catalogPath.c_str( ) );
    std::string catalogLine;

    // Check if catalog is 2-line or 3-line version.
    std::getline( catalogFile, catalogLine );
    const int tleLines = getTleCatalogType( catalogLine );

    // Reset file stream to start of file.
    catalogFile.seekg( 0, std::ios::beg );

    int numberOfPrunedObjects = 0;

    // Loop over file and apply filters to generate pruned catalog.
    if ( tleLines == 3 )
    {
        std::cout << "3-line catalog detected ..." << std::endl;

        std::ofstream prunedCatalogFile( input.prunedCatalogPath.c_str( ) );

        while ( std::getline( catalogFile, catalogLine ) )
        {
            if ( catalogLine.substr( 0, 1 ).compare( "0" ) != 0 )
            {
                // TODO: print catalog line in error message.
                throw std::runtime_error( "ERROR: Catalog malformed!" );
            }
            const std::string line0 = catalogLine;

            // Check regex name filter.
            // If regex can't be match, continue.
            boost::xpressive::sregex line0RegexFilter
                = boost::xpressive::sregex::compile( input.nameRegex.c_str( ) );
            if ( !boost::xpressive::regex_search( line0, line0RegexFilter ) )
            {
                std::getline( catalogFile, catalogLine );
                std::getline( catalogFile, catalogLine );
                continue;
            }

            std::getline( catalogFile, catalogLine );
            if ( catalogLine.substr( 0, 1 ).compare( "1" ) != 0 )
            {
                // Print catalog line in error message.
                throw std::runtime_error( "ERROR: Catalog malformed!" );
            }
            removeNewline( catalogLine );
            const std::string line1 = catalogLine;

            std::getline( catalogFile, catalogLine );
            if ( catalogLine.substr( 0, 1 ).compare( "2" ) != 0 )
            {
                // Print catalog line in error message.
                throw std::runtime_error( "ERROR: Catalog malformed!" );
            }
            removeNewline( catalogLine );
            const std::string line2 = catalogLine;

            // Create TLE object from catalog lines.
            const Tle tle( line0, line1, line2 );

            // Apply filters.
            const OrbitalElements orbitalElements( tle );

            // Apply semi-major axis filter.
            const double semiMajorAxis = orbitalElements.RecoveredSemiMajorAxis( ) * kXKMPER;
            if ( ( semiMajorAxis < input.semiMajorAxisMinimum + kXKMPER )
                 || ( semiMajorAxis > input.semiMajorAxisMaximum + kXKMPER ) )
            {
                continue;
            }

            // Apply eccentricity filter.
            const double eccentricity = orbitalElements.Eccentricity( );
            if ( ( eccentricity < input.eccentricityMinimum )
                 || ( eccentricity > input.eccentricityMaximum ) )
            {
                continue;
            }

            // Apply inclination filter.
            const double inclination = orbitalElements.Inclination( ) / kPI * 180.0;
            if ( ( inclination < input.inclinationMinimum )
                 || ( inclination > input.inclinationMaximum ) )
            {
                continue;
            }

            // Check if the number of objects in the pruned catalog has reached the cutoff set by
            // the user. If not, increment the counter.
            if ( input.catalogCutoff != 0 && numberOfPrunedObjects == input.catalogCutoff )
            {
                std::cout << "Cutoff reached ..." << std::endl;
                break;
            }

            numberOfPrunedObjects++;

            // This point is reached if TLE is not filtered: write catalog lines to pruned catalog.
            prunedCatalogFile << line0 << std::endl;
            prunedCatalogFile << line1 << std::endl;
            prunedCatalogFile << line2 << std::endl;
        }

        prunedCatalogFile.close( );
    }
    else if ( tleLines == 2 )
    {
        std::cout << "2-line catalog detected ... " << std::endl;
        std::cout << "WARNING: regex name filter will be skipped!" << std::endl;

        std::ofstream prunedCatalogFile( input.prunedCatalogPath.c_str( ) );

        while ( std::getline( catalogFile, catalogLine ) )
        {
            if ( catalogLine.substr( 0, 1 ).compare( "1" ) != 0 )
            {
                // Print catalog line in error message.
                throw std::runtime_error( "ERROR: Catalog malformed!" );
            }
            removeNewline( catalogLine );
            const std::string line1 = catalogLine;

            std::getline( catalogFile, catalogLine );
            if ( catalogLine.substr( 0, 1 ).compare( "2" ) != 0 )
            {
                // Print catalog line in error message.
                throw std::runtime_error( "ERROR: Catalog malformed!" );
            }
            removeNewline( catalogLine );
            const std::string line2 = catalogLine;

            // Create TLE object from catalog lines.
            const Tle tle( line1, line2 );

            // Apply filters.
            const OrbitalElements orbitalElements( tle );

            // Apply semi-major axis filter.
            const double semiMajorAxis = orbitalElements.RecoveredSemiMajorAxis( ) * kXKMPER;
            if ( ( semiMajorAxis < input.semiMajorAxisMinimum + kXKMPER )
                 || ( semiMajorAxis > input.semiMajorAxisMaximum + kXKMPER ) )
            {
                continue;
            }

            // Apply eccentricity filter.
            const double eccentricity = orbitalElements.Eccentricity( );
            if ( ( eccentricity < input.eccentricityMinimum )
                 || ( eccentricity > input.eccentricityMaximum ) )
            {
                continue;
            }

            // Apply inclination filter.
            const double inclination = orbitalElements.Inclination( ) / kPI * 180.0;
            if ( ( inclination < input.inclinationMinimum )
                 || ( inclination > input.inclinationMaximum ) )
            {
                continue;
            }

            // Check if the number of objects in the pruned catalog has reached the cutoff set by
            // the user. If not, increment the counter.
            if ( input.catalogCutoff != 0 && numberOfPrunedObjects == input.catalogCutoff )
            {
                std::cout << "Cutoff reached ..." << std::endl;
                break;
            }

            numberOfPrunedObjects++;

            // This point is reached if TLE is not filtered: write catalog lines to pruned catalog.
            prunedCatalogFile << line1 << std::endl;
            prunedCatalogFile << line2 << std::endl;
        }

        prunedCatalogFile.close( );
    }
    else
    {
        throw std::runtime_error( "ERROR: # of lines per TLE must be 2 or 3!" );
    }

    std::cout << "Number of objects in pruned catalog: " << numberOfPrunedObjects << std::endl;

    catalogFile.close( );
}
示例#9
0
int main() {
	//Get process id
	int pid = getpid();
	time_t t;
	
	//Initialize random number generator
	srand((unsigned) time(&t));
	
	//Char array of room names
	char *roomNames[] = {"Black", "White", "Silver", "Purple", "Orange", "Yellow", "Blue", "Green", "Brown", "Red"};
	int *roomNum[7];
	char *win[8];
	char dirname[50];
	
	//Create directory for room files
	sprintf(dirname, "flathm.rooms.%d", pid);
	int retval;
	retval = mkdir(dirname, 0777);
	if(retval != -1)
		//printf("Directory created!\n");
	
	//Create 7 rooms in directory, open each file and write contents: Assign random name, type, and connections
	FILE *fin, *fout;
	int i, rnum1, rnum2, rnum3, rnum4;
	char fname[50];
	
	//Generate contents of each file- name, connections, room_type
	for(i=0;i<7;i++) {
	
		sprintf(fname, "flathm.rooms.%d/Rm%d", pid, i);
		fin = fopen(fname, "w");
		if(!fin)
			printf("%s could not open", fname);
		
		if(i == 0) {
			// Generate Random Start room and 3 connections
			int j = 0;
			while (j != 1) {
				rnum1 = rand() % 10;
				rnum2 = rand() % 10;
				rnum3 = rand() % 10;
				rnum4 = rand() % 10;
				
				//Make sure each random room selection is different
				if(rnum1 == rnum2 || rnum1 == rnum3 || rnum1 == rnum4)
					j = 0;
				else if(rnum2 == rnum3 || rnum2 == rnum4)
					j = 0;
				else if(rnum3 == rnum4)
					j = 0;
				else 
					j = 1;
			}
			//Keep track of which files equal to which room names and their index numbers in roomNames array
			roomNum[i] = rnum1;
			win[i] = roomNames[rnum1];
			
			//**********Display the first file's room name
			//printf("\n%s is Room %d\n", roomNames[rnum1], i);
			
			//Write room name, connections, and room_type into file
			fprintf(fin, "ROOM NAME: %s\n", roomNames[rnum1]);
			fprintf(fin, "CONNECTION 1: %s\n", roomNames[rnum2]);
			fprintf(fin, "CONNECTION 2: %s\n", roomNames[rnum3]);
			fprintf(fin, "CONNECTION 3: %s\n", roomNames[rnum4]);
			fprintf(fin, "ROOM TYPE: %s\n", "START_ROOM");
				
		}
		//Randomly generate contents for files 2-6
		else if(i > 0 && i < 6) {
			int x;
			//Randomly choose a connection from one room to the next room
			x = (rand() % 3) + 1;
			if(x == 1)
				rnum1 = rnum2;
			else if(x == 2)
				rnum1 = rnum3;
			else if(x == 3)
				rnum1 = rnum4;
			else printf("Error! No connection to room 2 from room 1."); 
			
			int j = 0;
			while (j != 1) {
				
				rnum2 = rand() % 10;
				rnum3 = rand() % 10;
				rnum4 = rand() % 10;
				
				//Make sure each random room selection is different
				if(rnum1 == rnum2 || rnum1 == rnum3 || rnum1 == rnum4)
					j = 0;
				else if(rnum2 == rnum3 || rnum2 == rnum4)
					j = 0;
				else if(rnum3 == rnum4)
					j = 0;
				else 
					j = 1;
			}
			
			//Check if random selection is used already
			int m, numtaken;			
			for(m=0; m<=i; m++) {
				if(rnum1 == roomNum[m]) {
					numtaken = 1;
				}				
			}
			
			//If randomly selected room name has been used, then find and select unused room name
			if(numtaken == 1) {
				int y, z, unused;
				int index = 0;
				for(y=0; y<10; y++) {
					for(z=0;z<=i;z++) {
						if(roomNum[z] == y) {
								index++;
						}
						else {
							unused = y;
						}
					}
					if(index == 0) {
							rnum1 = unused;
					}
					index = 0;
				}
			}
				
			roomNum[i] = rnum1;
			win[i] = roomNames[rnum1];
			
			//**********Display which room/file equals which room name
			//printf("%s is Room %d\n", roomNames[rnum1], i);
			
			//Write randomly generated contents into files
			fprintf(fin, "ROOM NAME: %s\n", roomNames[rnum1]);
			fprintf(fin, "CONNECTION 1: %s\n", roomNames[rnum2]);
			fprintf(fin, "CONNECTION 2: %s\n", roomNames[rnum3]);
			fprintf(fin, "CONNECTION 3: %s\n", roomNames[rnum4]);
			if(roomNum[i-1] != rnum2 && roomNum[i-1] != rnum3 && roomNum[i-1] != rnum4)
				fprintf(fin, "CONNECTION 4: %s\n", win[i-1]);			//Connection back to previous room
			fprintf(fin, "ROOM TYPE: %s\n", "MID_ROOM");
			
		}
		//Generate random content for room/file 7
		else {
			int x;
			
			//Randomly choose a connection from room 6 to connect to room 7
			x = (rand() % 3) + 1;
			if(x == 1)
				rnum1 = rnum2;
			else if(x == 2)
				rnum1 = rnum3;
			else if(x == 3)
				rnum1 = rnum4;
			else printf("Error! No connection to room 6 from room 7.");
			
			//Generate random END_ROOM and 3 connections
			int j = 0;
			while (j != 1) {
				rnum2 = rand() % 10;
				rnum3 = rand() % 10;
				rnum4 = rand() % 10;
				
				//Make sure each random room selection is different
				if(rnum1 == rnum2 || rnum1 == rnum3 || rnum1 == rnum4)
					j = 0;
				else if(rnum2 == rnum3 || rnum2 == rnum4)
					j = 0;
				else if(rnum3 == rnum4)
					j = 0;
				else 
					j = 1;
			}
			
			//Check if random selection is used already
			int m, numtaken;			
			for(m=0; m<=i; m++) {
				if(rnum1 == roomNum[m]) {
					numtaken = 1;
				}				
			}
			
			//If randomly selected room name has been used, then find and select unused room name
			if(numtaken == 1) {
				int y, z, unused;
				int index = 0;
				for(y=0; y<10; y++) {
					for(z=0;z<=i;z++) {
						if(roomNum[z] == y) {
								index++;
						}
						else {
							unused = y;
						}
					}
					if(index == 0) {
							rnum1 = unused;
					}
					index = 0;
				}
			}
			
			roomNum[i] = rnum1;
			win[i] = roomNames[rnum1];
			
			//***********Display file 7's room name
			//printf("%s is Room %d\n", roomNames[rnum1], i);
			
			//Write randomly generated contents to file 7
			fprintf(fin, "ROOM NAME: %s\n", roomNames[rnum1]);
			fprintf(fin, "CONNECTION 1: %s\n", roomNames[rnum2]);
			fprintf(fin, "CONNECTION 2: %s\n", roomNames[rnum3]);
			fprintf(fin, "CONNECTION 3: %s\n", roomNames[rnum4]);
			if(roomNum[i-1] != rnum2 && roomNum[i-1] != rnum3 && roomNum[i-1] != rnum4)
				fprintf(fin, "CONNECTION 4: %s\n", win[i-1]);			//If there is none, write connection back to previous room
			fprintf(fin, "ROOM TYPE: %s\n", "END_ROOM");
			
		}
		
		fclose(fin);
	}
	
	/**********************************Start Game************************************/
	char *final[20];
	char Readfile[50];
	int n = 0;
	int steps = 0;
	char a[10], b[10], c[10];
	char name[10], con1[10], con2[10], con3[10], con4[10], con5[10];
	
	//Open START_ROOM 
	sprintf(Readfile, "flathm.rooms.%d/Rm0", pid);
	fout = fopen(Readfile, "r");
	
	//Open file, START_ROOM, and read contents - name, connection 1, 2, 3 into variables a, b, c
	if(fout != NULL) {
	
		while(fscanf(fout, "%s %s %s", &a, &b, &c) == 3) {
			
			if(n == 0)
				sprintf(name, "%s", c);
			else if(n == 1)
				sprintf(con1, "%s", c);
			else if(n == 2)
				sprintf(con2, "%s", c);
			else if(n == 3)
				sprintf(con3, "%s", c);
			else if(n == 4)
				sprintf(con4, "%s", c);
			else 
				sprintf(con5, "%s", c);
				
			n++;
		}
		rewind(fout);
		fclose(fout);
	}
	
	//Receive standard input for next room and check for correct input, otherwise report error.
	int correct = 0;
	char answer[10];
	
	while(correct != 1) {
		//Check number of connections and print accordingly
		if(n == 5) {
			printf("\n");
			printf("CURRENT LOCATION: %s\n", name);
			printf("POSSIBLE CONNECTIONS: %s, %s, %s.\n", con1, con2, con3);
			printf("WHERE TO? >");
		}
		else {
			printf("\n");
			printf("CURRENT LOCATION: %s\n", name);
			printf("POSSIBLE CONNECTIONS: %s, %s, %s, %s.\n", con1, con2, con3, con4);
			printf("WHERE TO? >");
		}
		
		//Get standard input
		fgets(answer, 10, stdin);
		removeNewline(answer, 10);
		
		//Check answer selection- answer must be of the three choices and include exact spelling.
		if(strcmp(answer, con1) == 0) {
			correct = 1;
		}
		else if(strcmp(answer, con2) == 0) {
			correct = 1;
		}
		else if(strcmp(answer, con3) == 0) {
			correct = 1;
			
		}
		else if (strcmp(answer, con4) == 0) {
			correct = 1;
		}
		else {
			printf("\n");
			printf("\nHUH? I DON'T UNDERSTAND THAT ROOM. TRY AGAIN.\n");
			printf("\n");
			
		}
		
	}
	
	int exit = 0;
	char openroom[50];
	char name2[10], connect1[10], connect2[10], connect3[10], connect4[10], connect5[10];
	
	//If the END_ROOM is located with first guess, do not enter into while loop.
	if(strcmp(answer, win[6]) == 0) {
		exit = 1;
	}
	//Run game until the END_ROOM is reached
	while(exit != 1) {
				
		int number, rm, k;
		
		//Search for file name that is equal to standard input- user's room selection.
		for(i = 0; i < 10; i++) {
			if(strcmp(answer, roomNames[i]) == 0) {
				number = i;
				final[steps] = roomNames[i];
				steps++;
				for(k = 0; k < 7; k++) {
					if(number == roomNum[k]) 
						rm = k;
				}
			}
		}
示例#10
0
int main()
{
	int i, j, k, l; // Iterators
	int valuesize;
	char strInput[LENGTH]; // Buffer for scanning string inputs
	int values[LENGTH][LENGTH]; // 2D Array to contain integer value equivalents
	int nattributes; // Number of attributes
	int nchoices; // Number of choices per attribute
	int nvalues; // Number of values in test data
	FILE * file;
	FILE * file2;
	att test;
	tree decisionTree;
	init(&test);
	initTree(&decisionTree);
	init(&glob);
	attnode * node;

	/*
		Format of input.txt:
			Outlook             // 1st Attribute
			3                   // Number of values for 1st attribute
			Sunny               // 1st value of 1st attribute
			Overcast            // 2nd value of 1st attribute
			Rain                // 3rd value of 1st attribute
			Temperature         // 2nd Attribute
			3                   // Number of values for 2nd attribute
			Hot                 // 1st value of 2nd attribute
			Mild                // 2nd value of 2nd attribute
			Cool                // 3rd value of 2nd attribute
	*/

	file=fopen("joinorg.txt", "r");
	if(file==NULL)
	{
		printf("Missing or empty file.\n");
		return 0;
	}

	fscanf(file, "%d\n", &nattributes);
	valuesize=1;
	j=-1;
	for(k=0; k<nattributes; k++)
	{
		fgets(strInput, LENGTH, file);
		removeNewline(strInput);
		addNode(&test, strInput, 0, k, j);
		j--;

		fscanf(file, "%d\n", &nchoices);
		for(i=0; i<nchoices; i++)
		{
			fgets(strInput, LENGTH, file);
			removeNewline(strInput);
			addNode(&test, strInput, i+1, k, valuesize);
			valuesize++;
		}
	}

	showList(&test);

	/*
		Format of inputvalues.txt:
		5                               // Number of values
		Sunny Hot High Light No         // 1st input value
		Sunny Hot High Strong No        // 2nd input value
		Overcast Hot High Light Yes     // 3rd input value
		Rain Mild High Light Yes        // 4th input value
		Rain Cool Normal Light Yes      // 5th input value
	*/

	file2=fopen("inputsurvey.txt", "r");
	if(file==NULL)
	{
		printf("Missing or empty file.\n");
		return 0;
	}

	fscanf(file2, "%d\n", &nvalues);
	attnode * curr;
	for(i=0; i<nvalues; i++)
	{
		for(j=0; j<nattributes; j++)
		{
			fscanf(file2, "%s ", strInput);
			curr=test.head;
			while(curr!=NULL)
			{
				if(strcmp(strInput, curr->attname)==0)
				{
					//printf("%s ", curr->attname);
					values[i][j]=curr->equivalent;
					break;
				}
				curr=curr->next;
			}

		}
		//printf("\n");
	}

	printf("\n");   

	/*for(i=0; i<nvalues; i++)
	{
		for(j=0; j<nattributes; j++)
		{
			printf("%d ", values[i][j]);
		}
		printf("\n");
	}*/

	addSubtree(0, values, nvalues, nattributes, &test, &decisionTree);
	node=glob.head;
	while(node!=NULL){
		addSubtree(node->equivalent, values, nvalues, nattributes, &test, &decisionTree);
		node=node->globnext;
	}

	node=glob.head;
	while(node!=NULL){
		printf("\n%s pos: %d, neg: %d\n", node->attname, node->positivetracker, node->negativetracker);
		node=node->globnext;
	}
	updatePosNeg(1, 8, values, nvalues, nattributes, &test);
	updatePosNeg(2, 8, values, nvalues, nattributes, &test);
	updatePosNeg(3, 8, values, nvalues, nattributes, &test);
}